Skip to content
Merged
Show file tree
Hide file tree
Changes from 6 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
27 changes: 25 additions & 2 deletions README-es.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,10 @@ const provider = new Provider(rpc, sender);
Si quieres firmar con Alice en un nodo local:

```ts
const rpc = "ws://127.0.0.1:37345";
import { Keyring } from '@polkadot/keyring'
import { cryptoWaitReady } from '@polkadot/util-crypto'

const rpc = "ws://127.0.0.1:37345"; // ws del nodo local
await cryptoWaitReady();

const keyring = new Keyring({ type: "sr25519" });
Expand All @@ -68,9 +71,27 @@ const provider = new Provider(rpc, sender);
Si quieres firmar con una semilla mnemotécnica

```ts
import { Keyring } from '@polkadot/keyring'


const sender = keyring.addFromMnemonic("<your mnemonic seed here>");
```

Si quieres firmar con la extensión de polkadotjs
```ts
import { web3FromAddress, web3Accounts, web3Enable } from "@polkadot/extension-dapp";

const extensions = await web3Enable("<your app name>");
const accounts = await web3Accounts();
const accountId = accounts[0].address;

const injector = await web3FromAddress(accountId);

const provider = new Provider(rpc, accountId);
provider.setSigner(injector.signer);
```


## Metodos soportados

<a href="https://wiki.polkadot.network/docs/learn-xcm#reserve-asset-transfer"> Reserve Asset Transfer </a> con los metodos reserveTransferAsset y LimitedReserveTransferAsset y <a href="https://wiki.polkadot.network/docs/learn-xcm#asset-teleportation">Asset teleportation </a> con los metodos teleportAsset y LimitedTeleportAsset.
Expand All @@ -96,6 +117,7 @@ provider.reserveTransferAssets(params);
<td>destination</td>
<td>El destino para transferir el activo. Si desea transferir activos de la cadena 'relay/principal' a una cadena 'parachain', configure 'Parachain'. Predeterminado 'Here'.</td>
</tr>
<tr>
<td>destinationParents</td>
<td>0 es el valor predeterminado, 1 cuando desea transferir de parachain a relaychain o de parachain a parachain</td>
</tr>
Expand All @@ -107,7 +129,7 @@ provider.reserveTransferAssets(params);
<td>beneficiary</td>
<td>objetivo del beneficiario, una accountId32</td>
</tr>
</tr>
<tr>
<td>beneficiaryParents</td>
<td>0 por defecto</td>
</tr>
Expand All @@ -119,6 +141,7 @@ provider.reserveTransferAssets(params);
<td>amount</td>
<td>cantidad de tokens a transferir</td>
</tr>
<tr>
<td>assetId</td>
<td>El identificador del asset para transferir desde una parachain, asegúrese de que la parachain admita el activo y que la cuenta del remitente tenga suficientes activos para transferir</td>
</tr>
Expand Down
41 changes: 31 additions & 10 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,22 +56,41 @@ const provider = new Provider(rpc, sender)
If you want to sign with Alice in a local node:

```ts
const rpc = "ws://127.0.0.1:37345"
await cryptoWaitReady();
import { Keyring } from '@polkadot/keyring'
import { cryptoWaitReady } from '@polkadot/util-crypto'

const keyring = new Keyring({ type: "sr25519" });
const sender = keyring.addFromUri("//Alice");
const rpc = "ws://127.0.0.1:37345" // local node ws
await cryptoWaitReady();

const provider = new Provider(rpc, sender);
const keyring = new Keyring({ type: "sr25519" });
const sender = keyring.addFromUri("//Alice");

const provider = new Provider(rpc, sender);

```

If you want to sign with mnemonic

```ts
const sender = keyring.addFromMnemonic(
"<your mnemonic seed here>"
);
import { Keyring } from '@polkadot/keyring'

const sender = keyring.addFromMnemonic(
"<your mnemonic seed here>"
);
```

If you want to sign with polkadotjs extension
```ts
import { web3FromAddress, web3Accounts, web3Enable } from "@polkadot/extension-dapp";

const extensions = await web3Enable("<your app name>");
const accounts = await web3Accounts();
const accountId = accounts[0].address;

const injector = await web3FromAddress(accountId);

const provider = new Provider(rpc, accountId);
provider.setSigner(injector.signer);
```

## Supported Methods
Expand Down Expand Up @@ -99,6 +118,7 @@ provider.reserveTransferAssets(params)
<td>destination</td>
<td>The destination to transfer the asset. If you want to transfer asset from relaychain to a parachain set 'Parachain'. Default 'Here'. </td>
</tr>
<tr>
<td>destinationParents</td>
<td>0 is default, 1 when you want to transfer from parachain to relaychain or parachain to parachain</td>
</tr>
Expand All @@ -110,7 +130,7 @@ provider.reserveTransferAssets(params)
<td>beneficiary</td>
<td>beneficary target, an accountId32</td>
</tr>
</tr>
<tr>
<td>beneficiaryParents</td>
<td>0 is default</td>
</tr>
Expand All @@ -122,6 +142,7 @@ provider.reserveTransferAssets(params)
<td>amount</td>
<td>token amount to transfer</td>
</tr>
<tr>
<td>assetId</td>
<td>AssetId to transfer from parachain, make sure the parchain support the asset and the sender account have enough asset to transfer</td>
</tr>
Expand All @@ -136,7 +157,7 @@ Depends on the parachain or relay chain configuration you have to use Asset tele

## Rococo examples

If you want to tests in Testnet, you have Rococo.
If you want to tests in Testnet, you have Rococo.
</br>
Get some assets: <a href="https://app.element.io/#/room/#rococo-faucet:matrix.org">Rococo faucet</a>

Expand Down
14 changes: 13 additions & 1 deletion src/provider.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { ApiPromise, WsProvider } from '@polkadot/api'
import { Signer } from '@polkadot/types/types'
import { AddressOrPair, MultiLocationTypes } from './interfaces/generics'
import { TransferAssetsProps, LimitedTransferAssetsProps } from './interfaces/methods'
import { getPallet } from './utils'
Expand All @@ -7,16 +8,23 @@ import { makeXcmVersionedMultiLocation, makeAsssetMultiAsset, formatExtrinsicRes
export class Provider {
rpc: string
signer: AddressOrPair
injectorSigner: Signer | null = null

constructor(rpc: string, signer: AddressOrPair) {
this.rpc = rpc
this.signer = signer
}

private async getApi() {
return await ApiPromise.create({
const api = await ApiPromise.create({
provider: new WsProvider(this.rpc),
})

if (this.injectorSigner) {
api.setSigner(this.injectorSigner)
}

return api
}

private prepareExtrinsic(props: LimitedTransferAssetsProps) {
Expand Down Expand Up @@ -68,6 +76,10 @@ export class Provider {
}
}

public async setSigner(signer: Signer) {
this.injectorSigner = signer
}

public async reserveTransferAssets(props: TransferAssetsProps) {
const api = await this.getApi()

Expand Down
19 changes: 18 additions & 1 deletion src/tests/mocks/provider-mocks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,11 +66,28 @@ export const xcmPalletMock = {
}),
limitedTeleportAssets: () => ({
signAndSend: (signer: any, cb: any) => {
const status = { isInBlock: true }
const status = { isInBlock: true, isFinalized: true }
const txHash = XCM_PALLET_RESPONSES.limitedTeleportAssets
const dispatchError = ''
const dispatchInfo = {}

return cb({
status,
txHash,
dispatchError,
dispatchInfo,
})
},
}),
limitedTeleportAssetsWithError: () => ({
signAndSend: (signer: any, cb: any) => {
const status = { isInBlock: true, isFinalized: true }
const txHash = XCM_PALLET_RESPONSES.limitedTeleportAssets
const dispatchError = {
toString: () => 'tx error',
}
const dispatchInfo = ''

return cb({
status,
txHash,
Expand Down
66 changes: 66 additions & 0 deletions src/tests/provider.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,72 @@ describe('Provider', () => {
expect(res).to.equal(XCM_PALLET_RESPONSES.limitedTeleportAssets)
})

it('should send teleport asset from parachain to relaychain account native format', async () => {
sinon.stub(ApiPromise, 'create').returns({
tx: {
xcmPallet: {
limitedTeleportAssets: xcmPalletMock.limitedTeleportAssets,
},
},
} as any)

const keyring = new Keyring.default({ type: 'sr25519' })
const sender = keyring.addFromMnemonic(chainSpecsMock.senderMnemonic)

const rpc = chainSpecsMock.parachainRpc
const destinationParents = 1
const beneficiary = 'AccountId32'
const beneficiaryValue = 'FtyTjdPJkMFnF9UjQ1g6owwRGsmMGGF11FSZnq84P3yYKRD'
const assetParents = 1
const amount = 50000000000

const provider = new Provider(rpc, sender)

const res = await provider.limitedTeleportAssets({
destinationParents,
beneficiary,
beneficiaryValue,
assetParents,
amount,
})
expect(res).to.equal(XCM_PALLET_RESPONSES.limitedTeleportAssets)
})

it('should show error after send tx', async () => {
sinon.stub(ApiPromise, 'create').returns({
tx: {
xcmPallet: {
limitedTeleportAssets: xcmPalletMock.limitedTeleportAssetsWithError,
},
},
} as any)

const keyring = new Keyring.default({ type: 'sr25519' })
const sender = keyring.addFromMnemonic(chainSpecsMock.senderMnemonic)

const rpc = chainSpecsMock.parachainRpc
const destinationParents = 1
const beneficiary = 'AccountId32'
const beneficiaryValue = 'FtyTjdPJkMFnF9UjQ1g6owwRGsmMGGF11FSZnq84P3yYKRD'
const assetParents = 1
const amount = 50000000000

const provider = new Provider(rpc, sender)

try {
await provider.limitedTeleportAssets({
destinationParents,
beneficiary,
beneficiaryValue,
assetParents,
amount,
})
assert.fail('actual', 'expected', "It shouldn't work ")
} catch (error) {
expect(error).to.equal('tx error')
}
})

it('should show error', async () => {
sinon.stub(ApiPromise, 'create').returns({
tx: {
Expand Down
15 changes: 5 additions & 10 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ export const makeXcmVersionedMultiLocation = ({

if (target === 'AccountId32') {
const account = String(value)
const isHex = account?.startsWith('0x')
const isHex = account.startsWith('0x')

const accountId = isHex ? value : u8aToHex(decodeAddress(account))

Expand Down Expand Up @@ -82,22 +82,17 @@ export const makeAsssetMultiAsset = ({
export const formatExtrinsicResponse = ({ api, res, rej, status, txHash, dispatchError, dispatchInfo }: any) => {
if (status.isInBlock || status.isFinalized) {
if (dispatchError) {
if (dispatchError.isModule) {
const decoded = api.registry.findMetaError(dispatchError.asModule)
const { docs, name, section } = decoded

rej(`${section}.${name}: ${docs.join(' ')}`)
} else {
rej(dispatchError.toString())
}
rej(dispatchError.toString())
} else if (dispatchInfo) {
res(txHash.toString())
}
}
}

export const getPallet = (api: ApiPromise) => {
if (!api.tx?.xcmPallet && !api.tx.polkadotXcm) {
const palletIsIncluded = Object.keys(api.tx).some((p) => ['xcmPallet', 'polkadotXcm'].includes(p))

if (!palletIsIncluded) {
throw new Error('xcmPallet or polkadotXcm unsupported')
}

Expand Down