-
Notifications
You must be signed in to change notification settings - Fork 2
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
base: dev
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
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, | ||
} | ||
|
||
|
||
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 | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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}`); | ||
} | ||
} | ||
|
||
} |
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}); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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); | ||
}) | ||
}) |
There was a problem hiding this comment.
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