How to generate polkadot, filecoin address from xpub - cryptography

I have a xpub(extended public key) right now,and I want use this xpub to generate a polkadot address. so in my wallet I can use this address receive dot coin.
function xpubToDotAddress(xpub){
...logic here;
return address;
}

Related

How to write caller address of a function in testing?

I have a function call like this:
await multisig.connect(acc5).verify(from,to,value,_signature)
i want to check that caller address of the verify() is equal to the from, how can i write this in ether.js??
I am expecting acc5 is equal to from, how to check this in testing??
Each ethers account is an object that contains property address. So you can validate acc5.address against the from value.
const isTheSame = acc5.address == from;

DDD: Can I pass a Domain-Service as a parameter of aggregate constructor

I have a domain that maintains accounts for other systems(Media).
At first, I derived the following aggregate root
public class Account extends Entity {
private AccountId accountId;
private TenantId tenantId;
private LoginAccount loginAccount;
private Media media;
private LoginValidity validity;
public Account(TenatId shopId, Media media, LoginAccount loginAccount) {
this.accountId = new AccountId();
this.setTenatId(shopId);
this.set(media);
this.setLoginValidity(LoginValidity.NOT_REQUESTED);
}
public void validateLogin(LoginValidationService loginValidationService) {
LoginValidity validity = loginValidationService.validateLoginFor(media,loginAccount);
setLoginValidity(validity);
//TO-DO EVENT PUBLISHING
}
public void changeLoginAccount(LoginAccount loginAccount) {
setLoginAccount(loginAccount);
setLoginValidity(LoginValidity.NOT_REQUESTED);
//TO-DO EVENT PUBLISHING?
}
...Setters
}
And I also derived the LoginValidationService as a Domain-Service.
LoginValidationService determines strategy(policy) using Media
And then I also derive two business logic(invariant)
When the User adds a Account login validation must occur.
When the User changes LoginAccount login validation must occur.
My question is that for the first invariant,LoginValidationService(A Domain-Service) could be a parameter for aggregate root's constructor like this
public class AccountApplicationService {
private LoginValidationService loginValidationService;
private AccountRepository accountRepository;
public Account createAccount(CreateAccountCommand command) {
TenantId tenantId = new TenantId(command.getTenantId());
Media media = mediaService.mediaFrom(command.getMediaId());
Account account = new Account(tenantId,
media,
command.getLoginAccount(),
loginValidationService);
accountRepository.save(account);
return ccount;
}
...
}
public class Account extends Entity {
private AccountId accountId;
private TenantId tenantId;
private LoginAccount loginAccount;
private Media media;
private LoginValidity validity;
public Account(TenatId shopId,
Media media,
LoginAccount
loginAccount,LoginValidationService loginValidationService) {
this.accountId = new AccountId();
this.setTenatId(shopId);
this.set(media);
LoginValidity validity =
loginValidationService.validateLoginFor(media,loginAccount);
this.setLoginValidity(validity);
}
....
}
Is exist the Pattern above? (passing the domain-service to the constructor) and is it the right approach of DDD?
Do I have to derive the first invariant as a use-case? like this,
public class AccountApplicationService {
private LoginValidationService loginValidationService;
private AccountRepository accountRepository;
public Account createAccountAndValidateLogin(CreateAccountAndValidateLoginCommand command) {
TenantId tenantId = new TenantId(command.getTenantId());
Media media = mediaService.mediaFrom(command.getMediaId());
MediaAccount mediaAccount = new MediaAccount(tenantId,media,command.getLoginAccount());
mediaAccount.validateLogin(loginValidationService);
mediaAccountRepository.save(mediaAccount);
}
...
}
Please give me any advice.
-----------Edit---------
I add the Account's constructor code. LoginValidationService is not a member of Account.
Would be a solution for you to pass the LoginValidity as Account aggregate constructor parameter?
public Account createAccount(CreateAccountCommand command) {
TenantId tenantId = new TenantId(command.getTenantId());
Media media = mediaService.mediaFrom(command.getMediaId());
LoginValidity loginValidity =
loginValidationService.validateLoginFor(media,command.getLoginAccount());
Account account = new Account(tenantId,
media,
command.getLoginAccount(),
loginValidity);
accountRepository.save(account);
return ccount;
}
I think that to validate an account is something that the entity cannot do by yourself so it is clear is domain service's responsibility, then I would see in the use case flow logic, or you can create the account with a domain service responsible of validate and create the account and you had the business logic encapsulates in domain service instead of use case.
Can I pass a Domain-Service as a parameter of aggregate constructor
Yes, but I would expect that to make your life harder in the long run.
An AGGREGATE is a cluster of associated objects that we treat as a unit for the purpose of data changes. -- Evans, 2003
Domain Services, however, don't change -- they are stateless, and "any client can use any instance of a particular SERVICE without regard to the instance's individual history."
So mixing the patterns in this way is a bit odd on two fronts; including the service as a member of the aggregate suggests that it changes, and also it implies that this aggregate has a special relationship with a particular instance of the service, which contradicts the notion that they are not interchangeable.
It's not clear to me what compensating advantage you get in a design where the service is embedded within your aggregate.
I found an additional invariant for Account creating that Account can't hold itself so I derived AccountProvisionService(Domain-Service). The Application-Service code is as follows.
...
public Account createAccount(CreateAccountCommand command) {
return AccountProvisioningService.provisionAccount(
command.getTenantId(), command.getMediaId(), command.getLoginAccount());
}
public void changeLoginAccount(ChangeLoginAccountCommand command) {
Account account = existingAccount(command.getShopId(),command.getAccountId());
LoginValidity loginValidity = loginValidationService.validateLoginFor(Account.media(), command.getLoginAccount());
account.changeLoginAccount(command.getLoginAccount(),loginValidity);
AccountRepository.save(account);
}
...

Create map of existing objects in mint function for a smart contract

I'm really new to solidity and there is still alot I dont fully get. I have created this smart contract. I am getting an error while performing a test stating that the id to be set by the push cant be performed due to the following:
Error: Different number of components on the left hand side (1) than on the right hand side (0).
uint _id = arts.push(_art);//create ids
^------------------------^
I understand that the push receives only one atribute and should be able to stablish the index to the id variable. Nontheless this bugg occurs, I'm not sure if its the version or something else. I'm currently using truffle for the tests with version: "^0.6.0". I would really appreciate your help. Thanks in advance!
Here's my code:
pragma solidity >=0.4.21 <0.7.0;
import "#openzeppelin/contracts/token/ERC721/ERC721.sol";
contract Art is ERC721{
string[] public arts;
mapping(string => bool) _artExists;//similar to json or hash
constructor() ERC721("Art", "DATA") public {
}
//E.G color = "#FFFFFF"
//create art restrict in the future to mentors
function mint(string memory _art) public{
//Require unique Art
require(!_artExists[_art]);
uint _id = arts.push(_art);//create ids
//address
_mint(msg.sender, _id);
_artExists[_art] = true;
//Art - track it & add it
//Call the mint function
//Art - track it
}
}
//mint function
push()
returns a reference to the new added element, not the index.
Exemple :
arts.push() = "whatever you want";
Use the length attribute to get the index or the new element.

How can I set a list with different expiration of its child?

Now I need to make a IP black list demand.
When the administer add the ip address to the IP black list, the IP can not access the website within 2 hours.
In my opinion, I will use a ImemoryCache and set a expiration to store it. Meanwhile, one key of ImemoryCache can only store one object and set one expiration while there may be so many IP address here..
How can I set a list with different expiration of its child? Thank you.
How can I set a list with different expiration of its child?
You could not set different expiration for the child if you cache the IP List with one key.
For a workaround, you may try to cache the ip independent like below:
public IActionResult CreateCache()
{
string ip = "xx.xx";
using (var entry = _memoryCache.CreateEntry(ip))
{
entry.SlidingExpiration = TimeSpan.FromHours(2);
}
return Ok();
}
public IActionResult CheckCache()
{
string ip = "xx.xx";
var exist = _memoryCache.TryGetValue(ip, out string value);
return Ok();
}

Grails 3: using findAll with join tables

In my Grails webapp I have the following domain classes:
class Customer {
static hasMany = [
addresses: Address
]
static mapping = {
addresses (cascade: "all-delete-orphan", joinTable: [name: "bs_core_customer_addresses"])
}
}
class Address {
...
}
Now I want to implement the abillity to filter the 1:n relation like addresses for things like country (should be dynamic, that means the user can add different filters by itself).
What is the best way to accomplish this?
Filtering the collection from the Customer object? e.g. customer.addresses.findAll{...}
Direct query from the database? How can I add the restriction for the Customer<->Address relation. belongsTo at the Address domain class is no option because the Address object is used in several 1:n relations. e.g. Customer.findAll(...)
Any other option?
you should be able to get away with
static constraints = {
addresses(validator: checkAddress)
}
// This is a static method which is used for validation
// and can be used for when inserting a record to check how many
// existing addresses exist for the end user that has countryCode of US
// This is directly bound to all the object the user and will
// will not be searching the entire DB (A local find limited to user records)
static def checkAddress={val,obj,errors->
if (!obj?.addresses.findAll{it.countryCode=='US'}?.size() >= 2) {
return errors.rejectValue('adress','exceeds limit')
}
}
The above should be self explanatory, but having read through your post a few times now I think I have a better understanding of what you are trying to achieve and there are probably a few different ways of doing it. So let's explore some of them:
Using HQL query, you could change this to another method, I prefer HQL.
class Customer {
def userService
//UserAddress does not have setter transients not essential
static transients = ['userAddress','userService']
//This is a protected function that will return an address
// object given a countryCode
// Execute like this:
// Customer cm = Customer.get(customer.id as Long)
//Address usa = cm.getCountry('US')
protected Address getUserAddress(String countryCode) {
return userService.findAddress(countryCode, this.id)
}
}
Now the service but actually you don't need to execute in domain class unless there is some other need, for displaying etc you could always call this sort of service from within a controller call to render for display purposes
class UserSerice {
// This should return the entire address object back to the domain class
// that called it and will be quicker more efficient than findAll
Address findAddress(String countryCode, Long customerId) {
String query="""
select address from Address a
where a.id :id and countryCode = :code
"""
def inputParams=[code:countryCode, id:customerId]
return Address.executeQuery(query,inputParams,[readOnly:true,timeout:15])
}
Another approach could be a 3rd table that gets updated upon each address added that would give a quick lookup:
class Customer {
static hasMany = [
addresses: Address
//probably don't even need this
//, userCountries:UserCountries
]
}
Class UserCountries {
// register customer
Customer customer
String CountryCode
//maybe address object or Long addressId - depending on if how plain you wanted this to be
Address address
}
Then register the address id and countryCode to this domainclass each time you add a new address and I guess you would need to write some backward compatible code to add existing records to this table for it to work properly.
I left a comment and then removed it for you to expand further on what or how the filtering was taking place. since although you talk of countryCode there is no actual code to show how it all fits in.
I still think something as simple as this would work
//This would only be doing a find with all the bound objects of addresses bound to this customer. so a find within the hasMany relationship elements of this specific customer
protected def getCustomAddress(String countryCode) {
return addresses.findAll{it.code==countryCode}
}
Other far out ideas could be something like this
class Customer {
String _bindAddress
List bindAddress=[]
static transients = [ 'bindAddress' ]
static constraints = {
_bindAddress(nullable:true)
}
//you store a flat CSV as _bindAddress
//you need to work out your own logic to ammend to existing CSV each time address is added
// you will also update _bindAddress of this domainClass each time customer gets a hasMany address added
// so no need for setBindAddress
// void setBindAddress(String b) {
// bindAddress=b.split(',')
// }
//Inorder to set a list back to flat file
//pass in list object
void setBindAddress(List bindAddress) {
_bindAddress=bindAddress.join(',')
/for 1 element this captures better
//_bindAddress=bindAddress.tokenize(',').collect{it}
}
//This is now your object as a list that you can query for what you are querying.
List getBindAdress() {
return _bindAddress.split(',')
}
}
If your actual csv list contained a listing of 'COUNTRY_CODE-ADDRESS_ID' then you could query like this
def found = customer.bindAddress.find{it.startsWith('US-')}
Address usaAddress= Address.get(found.split('-')[1] as Long)
//Slightly longer explaining above:
def found = customer.bindAddress.find{it.startsWith('US-')}
def record = found.split('-')
String countryCode=record[0]
Long addressId=record[1] as Long
Address usaAddress= Address.get(addressId)