Send tokens using evmosjs and eth-sig-util

This commit is contained in:
nabarun 2022-03-29 16:31:23 +05:30 committed by Ashwin Phatak
parent 6871e35964
commit 72ab467d9b
5 changed files with 1069 additions and 82 deletions

View File

@ -14,17 +14,27 @@ Follow these steps to run the tests:
- Run the chain using `./init.sh`.
- The mnemonic phrase can be seen in the console at the start just after the script is executed.
- Add a second account with the following:
```bash
ethermintd keys add <KEY_NAME> --keyring-backend test
```
- Copy the mnemonic phrase and assign it to variable `MNEMONIC` in the [test file](./src/index.test.ts).
- Get the account details using:
```bash
ethermintd keys list
```
- To export the private key run:
- Use the address of key `mykey` as the sender address. Copy the address and assign it to `SENDER_ADDRESS` in the [test file](./src/index.test.ts).
- Copy the address of other account and assign it to variable `TO_ADDRESS` in [test file](./src/index.test.ts).
- To export the sender private key run:
```bash
ethermintd keys export mykey --unarmored-hex --unsafe
```
- Copy the private key and assign it to variable `PRIVATE_KEY` in the [test file](./src/index.test.ts).
- Copy the private key and assign it to variable `SENDER_PRIVATE_KEY` in the [test file](./src/index.test.ts).
- Run the test in chiba-clonk-client repo:
@ -32,8 +42,11 @@ Follow these steps to run the tests:
yarn test
```
- The account details can be seen using
- Check account balances after running test:
```bash
ethermintd keys list
ethermintd query bank balances <ADDRESS>
# Example
ethermintd query bank balances ethm1ayxjyxxa3z9z0rjff7rpr67h8aqfgn2t9009zc
```

View File

@ -8,11 +8,16 @@
"@types/jest": "^27.4.1",
"jest": "^27.5.1",
"ts-jest": "^27.1.3",
"ts-node": "^10.7.0",
"typescript": "^4.6.2"
},
"dependencies": {
"@cosmjs/proto-signing": "^0.28.0",
"@cosmjs/stargate": "^0.28.0"
"@cosmjs/stargate": "^0.28.0",
"@metamask/eth-sig-util": "^4.0.0",
"axios": "^0.26.1",
"ethers": "^5.6.1",
"evmosjs": "^0.2.2"
},
"scripts": {
"test": "jest"

View File

@ -1,32 +1,9 @@
import { DirectSecp256k1HdWallet, DirectSecp256k1Wallet } from '@cosmjs/proto-signing';
import { stringToPath } from '@cosmjs/crypto';
import { fromHex } from '@cosmjs/encoding';
import { sendTokens } from './index'
const MNEMONIC = "talent dismiss teach girl mutual arctic burger matrix outdoor rude vapor rose boost drastic glimpse govern illness rhythm avoid fetch derive increase harvest oak";
const SENDER_ADDRESS = 'ethm1ayxjyxxa3z9z0rjff7rpr67h8aqfgn2t9009zc';
const SENDER_PRIVATE_KEY = '5041b1ace7ea207794f4c5c1c5f987ff8a9d782f194ef5b24bcffaafaf4a019f';
const TO_ADDRESS = 'ethm12x63cgg82ek97cf8ew9hf6r7je75s5w2smejqv';
const PRIVATE_KEY = "1c6dc846552186ef241489c4e4d10b01086d58b8c2ba06de5dfa589bd52cf23e"
describe('Send tokens', () => {
test('Create wallet using mnemonic', async () => {
const path = stringToPath("m/44'/60'/0'/0");
const wallet = await DirectSecp256k1HdWallet.fromMnemonic(
MNEMONIC,
{
prefix: 'ethm',
hdPaths: [path]
}
);
await sendTokens(wallet)
test('Send tokens', async () => {
await sendTokens(SENDER_PRIVATE_KEY, SENDER_ADDRESS, TO_ADDRESS)
});
test('Create wallet using private key', async () => {
const privateKey = fromHex(PRIVATE_KEY);
const wallet = await DirectSecp256k1Wallet.fromKey(privateKey, 'ethm')
await sendTokens(wallet)
});
})

View File

@ -1,36 +1,75 @@
import { OfflineDirectSigner } from "@cosmjs/proto-signing";
import { assertIsDeliverTxSuccess, SigningStargateClient } from "@cosmjs/stargate";
import axios from "axios";
import { generateEndpointAccount, generateEndpointBroadcast, generatePostBodyBroadcast } from '@tharsis/provider';
import { createMessageSend, createTxRawEIP712, signatureToWeb3Extension } from '@tharsis/transactions'
import { MessageTypes, signTypedData, SignTypedDataVersion } from "@metamask/eth-sig-util";
const RPC_ENDPOINT = "http://127.0.0.1:26657"
const ETHERMINT_REST_ENDPOINT = 'http://127.0.0.1:1317'
export const sendTokens = async (wallet: OfflineDirectSigner) => {
const [firstAccount] = await wallet.getAccounts();
console.log("account", firstAccount)
const client = await SigningStargateClient.connectWithSigner(RPC_ENDPOINT, wallet, { prefix: 'ethm' });
const senderAddress = firstAccount.address
const recipient = "ethm1xv9tklw7d82sezh9haa573wufgy59vmwe6xxe5";
const amount = {
denom: "ethm",
amount: "12345",
};
const sendMsg = {
typeUrl: "/ethm.bank.v1beta1.MsgSend",
value: {
fromAddress: senderAddress,
toAddress: recipient,
amount: [amount],
},
};
const defaultFee = {
amount: [],
gas: "200000",
};
const result = await client.signAndBroadcast(senderAddress, [sendMsg], defaultFee);
assertIsDeliverTxSuccess(result);
interface TypedMessageDomain {
name?: string;
version?: string;
chainId?: number;
verifyingContract?: string;
salt?: ArrayBuffer;
}
export const sendTokens = async (senderPrivateKey: string, senderAddress: string, destinationAddress: string) => {
let { data: addrData} = await axios.get(`${ETHERMINT_REST_ENDPOINT}${generateEndpointAccount(senderAddress)}`)
const chain = {
chainId: 9000,
cosmosChainId: 'ethermint_9000-1',
}
const sender = {
accountAddress: addrData.account.base_account.address,
sequence: addrData.account.base_account.sequence,
accountNumber: addrData.account.base_account.account_number,
pubkey: addrData.account.base_account.pub_key.key,
}
const fee = {
amount: '20',
denom: 'aphoton',
gas: '200000',
}
const memo = ''
const params = {
destinationAddress: destinationAddress,
amount: '10',
denom: 'aphoton',
}
// Create a MsgSend transaction.
const msg = createMessageSend(chain, sender, fee, memo, params)
const eipMessageDomain: any = msg.eipToSign.domain;
// Sign transaction.
const signature = signTypedData({
data: {
types: msg.eipToSign.types as MessageTypes,
primaryType: msg.eipToSign.primaryType,
domain: eipMessageDomain as TypedMessageDomain,
message: msg.eipToSign.message as Record<string, unknown>
},
privateKey: Buffer.from(senderPrivateKey, 'hex'),
version: SignTypedDataVersion.V4
})
let extension = signatureToWeb3Extension(chain, sender, signature)
// Create the txRaw
let rawTx = createTxRawEIP712(msg.legacyAmino.body, msg.legacyAmino.authInfo, extension)
const body = generatePostBodyBroadcast(rawTx)
// Broadcast it
await axios.post(
`${ETHERMINT_REST_ENDPOINT}${generateEndpointBroadcast()}`,
JSON.parse(body)
)
// TODO: Check for successful broadcast
}

979
yarn.lock

File diff suppressed because it is too large Load Diff