Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feature/1208492315807986 Address unification in SDK #32

Open
wants to merge 3 commits into
base: dev
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
98 changes: 98 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
"repository": "https://github.com/peaqnetwork/peaq-js.git",
"dependencies": {
"@polkadot/api": "12.4.2",
"ethers": "^6.13.3",
"peaq-did-proto-js": "^2.1.0",
"uuid": "^9.0.0"
},
Expand Down
3 changes: 3 additions & 0 deletions packages/sdk/src/modules/main/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import type { Options, SDKMetadata } from '../../types';

import { Base } from '../base';
import { GenerateDidOptions, GenerateDidResult, Did } from '../did';
import { Unification } from "../unification";
import { RBAC } from "../rbac";
import { Storage } from "../storage";

Expand All @@ -20,6 +21,7 @@ export class Main extends Base {
private _metadata: SDKMetadata;

public did: Did;
public unification: Unification;
public rbac: RBAC;
public storage: Storage;

Expand All @@ -30,6 +32,7 @@ export class Main extends Base {
this._metadata = {};

this.did = new Did(this._api, this._metadata);
this.unification = new Unification(this._api, this._metadata);
this.rbac = new RBAC(this._api, this._metadata);
this.storage = new Storage(this._api, this._metadata);
}
Expand Down
138 changes: 138 additions & 0 deletions packages/sdk/src/modules/unification/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
import { Base } from '../base';
import { ApiPromise } from '@polkadot/api';
import { decodeAddress } from '@polkadot/keyring';
import type { ISubmittableResult } from '@polkadot/types/types';

import { ChainIdError, CreateKeyBindError, ClaimAccountError, GenerateSignatureError } from '../../utils/errors';
import type { SDKMetadata } from '../../types';
import { ethers, Wallet } from "ethers";

interface ClaimAccountOptions {
network: string;
substrateSeed: string;
ethPrivate: string;
}

interface ClaimAccountResult {
message: string;
evm: string;
substrate: string;
}

enum ChainID {
AGUNG = 9990,
KREST = 2241,
PEAQ = 3338,
}

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Create new enum type to define network in the claim account options


export class Unification extends Base {
constructor(
protected override readonly _api?: ApiPromise,
protected readonly _metadata?: SDKMetadata,

) {
super();
}

/**
* Binds a SS58 Substrate wallet to a newly created H160 Ethereum wallet using the address unification pallet peaq provides.
* Make sure the H160 wallet is new and has no transactions.
*
* @param options ClaimAccountOptions - The options for binding the addresses.
* @returns CreateDidResult - Contains the block_hash of the executed transaction and unsubscribe() to terminate event listening.
*/
public async claimAccount(options: ClaimAccountOptions, statusCallback?: (result: ISubmittableResult) => void | Promise<void>): Promise<ClaimAccountResult> {
irediaes marked this conversation as resolved.
Show resolved Hide resolved
try {
const api = this._getApi();

const { network, substrateSeed, ethPrivate } = options;
if (!network) throw new Error("Error: No network provided.");
if (!substrateSeed) throw new Error("Error: No substrate private key provided.");
if (!ethPrivate) throw new Error("Error: No ethereum private key provided.");

const keyPair = this._getKeyPair(substrateSeed);
const ss58Address = keyPair.address;

const signer = new ethers.Wallet(ethPrivate);
const evmAddress = signer.address;

const ethSignature = await this._createKeyBind(network, ss58Address, signer);

const attributeExtrinsic = api.tx?.['addressUnification']?.['claimAccount'](
evmAddress,
ethSignature
);

const nonce = await this._getNonce(keyPair.address);
const eventData = await this._newSignTx({nonce, address: keyPair, extrinsics: attributeExtrinsic});
const unsubscribe = await attributeExtrinsic.send((result) => {
statusCallback &&
statusCallback(result as unknown as ISubmittableResult);
});

return {
message: "Address Unification Successful.",
evm: `${evmAddress}`,
substrate: `${ss58Address}`
}
} catch (error) {
if (typeof error === 'object' && error !== null && 'data' in error) throw new ClaimAccountError(`${error.data}`);
throw new ClaimAccountError(`${error}`);
}
}

protected async _createKeyBind(network: string, ss58Address: string, signer: Wallet): Promise <string>{
try {
const api = this._getApi();

// get chain name from api to check against what the user manually set
const properties = await api.rpc.system.properties();
const readable = properties.toHuman();

// want to make sure the set network is a known enum, and the set network is the same as the api metadata
if (ChainID[network.toUpperCase() as keyof typeof ChainID] == undefined
Copy link
Contributor Author

@jpgundrum jpgundrum Dec 3, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is where the check takes place. It first makes sure the network string is in the enum, and then compares to the currently connected api in the metadata to see if they align. Checking api instance before reduces amount of erroneous calls to chain.

|| (readable["tokenSymbol"] as string[])[0] != network.toUpperCase()) {
throw new ChainIdError(`Network mismatch. Make sure you correctly set your network parameter to either agung, krest, or
peaq based on the base url set during SDK initialization.`);
}
const chainId = ChainID[network.toUpperCase() as keyof typeof ChainID];

const signature = await this._generateSignature(
signer,
ss58Address,
chainId.toString()
);

return signature;

} catch (error){
throw new CreateKeyBindError(`${error}`);
}
}

protected async _generateSignature(signer: Wallet, ss58Address: string, chainId: string) {
try {
const api = this._getApi();
const blockHash = await api.rpc.chain.getBlockHash(0);

return await signer.signTypedData(
{
name: "Peaq EVM claim",
irediaes marked this conversation as resolved.
Show resolved Hide resolved
version: "1",
chainId: chainId,
salt: blockHash,
},
{
Transaction: [{ type: "bytes", name: "substrateAddress" }],
},
{
substrateAddress: decodeAddress(ss58Address),
}
);
} catch (error){
throw new GenerateSignatureError(`${error}`);
}
}

}
60 changes: 60 additions & 0 deletions packages/sdk/src/modules/unification/unification.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import { Keyring } from '@polkadot/keyring';
import { KeyringPair } from '@polkadot/keyring/types';
import { cryptoWaitReady } from '@polkadot/util-crypto';
import { Main as SDK } from '../main';

import dotenv from 'dotenv';
dotenv.config(); // Load variables from .env file

const SEED = process.env['SEED3'] as string;
const ETH_PRIVATE = process.env['ETH_PRIVATE2'] as string;
const BASE_URL = process.env['BASE_URL'] as string;
const EVM_ADDRESS = process.env['EVM_ADDRESS2'] as string;
const SUBSTRATE_ADDRESS = process.env['SUBSTRATE_ADDRESS2'] as string;


/**
* Performs tests when executing unification for SS58 to H160 addresses.
*
* To execute correctly make sure the EVM address on the network has no previous transactions.
*/
describe('Unification', () => {
let keyring: Keyring;
let user: KeyringPair;
let sdk: SDK;

beforeAll(async () => {
keyring = new Keyring({ type: 'sr25519' });
await cryptoWaitReady();
user = keyring.addFromUri(SEED);
sdk = await SDK.createInstance({baseUrl: BASE_URL, seed: SEED});
}, 40000);


/**
* Test suite for the executing expected operations.
*
* 1. Make sure setting an incorrect network name performs no transactions
* 2. Create a bind to an SS58 to H160 wallet
* 3. Error when a keybind has been created previously
*/
describe('create binds', () => {
it('incorrect network name', async () => {
await expect(sdk.unification.claimAccount({network: "random", substrateSeed: SEED, ethPrivate: ETH_PRIVATE}))
.rejects.toThrow(new Error(`CreateKeyBindError: ChainIdError: Network mismatch. Make sure you correctly set your network parameter to either agung, krest, or
peaq based on the base url set during SDK initialization.`));
}, 50000);
// works when I create an ETH wallet from scratch that has no previous transactions on the network
// and when you first setup an initial keybind... make sure the baseUrl that you initialize to matches the network you are claiming the account with
it('known ss58 to newly created known h160 bind', async () => {
const result = await sdk.unification.claimAccount({network: "krest", substrateSeed: SEED, ethPrivate: ETH_PRIVATE});
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@irediaes See how the use must manually set the network in the cmd. The backend code then checks the metadata api to see if the connected instance is on this same network.

Should we only use the metadata (initialized with sdk creation line 30) to get the chain id, or continue to use the network parameter that will be checked against the metadata?

expect(result.message).toBe("Address Unification Successful.");
expect(result.evm).toBe(EVM_ADDRESS);
expect(result.substrate).toBe(SUBSTRATE_ADDRESS);
}, 80000);
it('Expect an error when a previous keybind has already been created', async () => {
await expect(sdk.unification.claimAccount({network: "krest", substrateSeed: SEED, ethPrivate: ETH_PRIVATE}))
.rejects.toThrow(new Error(`Error: AccountIdHasMapped for addressUnification.`));
}, 50000);
})
})
34 changes: 34 additions & 0 deletions packages/sdk/src/utils/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -117,4 +117,38 @@ export class StorageSeedError extends StorageError {
this.name = 'StorageSeedError'; // Set the name property to the custom error type
Object.setPrototypeOf(this, new.target.prototype); // Restore the prototype chain
}
}


// Address Unification Errors
export class ChainIdError extends Error {
constructor(message: string) {
super(message);
this.name = 'ChainIdError';
Object.setPrototypeOf(this, new.target.prototype);
}
}

export class CreateKeyBindError extends Error {
constructor(message: string) {
super(message);
this.name = 'CreateKeyBindError';
Object.setPrototypeOf(this, new.target.prototype);
}
}

export class GenerateSignatureError extends Error {
constructor(message: string) {
super(message);
this.name = 'GenerateSignatureError';
Object.setPrototypeOf(this, new.target.prototype);
}
}

export class ClaimAccountError extends Error {
constructor(message: string) {
super(message);
this.name = 'ClaimAccountError';
Object.setPrototypeOf(this, new.target.prototype);
}
}