This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require('dotenv').config(); | |
const { ApiPromise, WsProvider, Keyring } = require('@polkadot/api'); | |
const { blake2AsU8a } = require('@polkadot/util-crypto'); | |
const BN = require('bn.js'); | |
const bn1e12 = new BN(10).pow(new BN(12)); | |
function getPhaAssetId(khalaApi) { | |
return khalaApi.createType('XcmV1MultiassetAssetId', { | |
Concrete: khalaApi.createType('XcmV1MultiLocation', { | |
parents: 0, | |
interior: khalaApi.createType('Junctions', 'Here') | |
}) | |
}) | |
} | |
// Make sure amount > bridge fee | |
async function transferPhaFromKhalaToEvm(khalaApi, sender, recipient, amount) { | |
console.log(`Transfer PHA from Khala to EVM...`); | |
return new Promise(async (resolve) => { | |
const unsub = await khalaApi.tx.xTransfer.transfer( | |
khalaApi.createType('XcmV1MultiAsset', { | |
id: getPhaAssetId(khalaApi), | |
fun: khalaApi.createType('XcmV1MultiassetFungibility', { | |
Fungible: khalaApi.createType('Compact<U128>', amount) | |
}) | |
}), | |
khalaApi.createType('XcmV1MultiLocation', { | |
parents: 0, | |
interior: khalaApi.createType('Junctions', { | |
X3: [ | |
khalaApi.createType('XcmV1Junction', { | |
GeneralKey: '0x7762' // string "wb", indentity of WanBridge path | |
}), | |
khalaApi.createType('XcmV1Junction', { | |
GeneralIndex: 0 // 0 is chainid of ethereum | |
}), | |
khalaApi.createType('XcmV1Junction', { | |
GeneralKey: recipient // EVM address, 20 bytes hex string | |
}), | |
] | |
}) | |
}), | |
null, // No need to specify a certain weight if transfer will not through XCM | |
).signAndSend(sender, (result) => { | |
if (result.status.isInBlock) { | |
console.log(`Transaction included at blockHash ${result.status.asInBlock}`); | |
} else if (result.status.isFinalized) { | |
console.log(`Transaction finalized at blockHash ${result.status.asFinalized}`); | |
unsub(); | |
resolve(); | |
} | |
}); | |
}); | |
} | |
async function main() { | |
// create khala api | |
const khalaEndpoint = process.env.ENDPOINT || 'ws://localhost:9944'; | |
const khalaProvider = new WsProvider(khalaEndpoint); | |
const khalaApi = await ApiPromise.create({ | |
provider: khalaProvider, | |
}); | |
const keyring = new Keyring({ type: 'sr25519' }); | |
const khalaAccount = keyring.addFromUri('//Alice'); | |
const evmRecipient = "0xA29D4E0F035cb50C0d78c8CeBb56Ca292616Ab20"; | |
// Transfer 50 PHA from Khala::Alice to Ethereum::0xA29D4E0F035cb50C0d78c8CeBb56Ca292616Ab20 | |
await transferPhaFromKhalaToEvm(khalaApi, khalaAccount, evmRecipient, bn1e12.mul(new BN(50))); | |
} | |
main().catch(console.error).finally(() => process.exit()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment