|
1 | 1 | import { Datagram } from "./datagram/index"; |
| 2 | +import { SDK } from "codechain-sdk"; |
| 3 | +import { H256, PlatformAddress } from "codechain-primitives"; |
| 4 | +import { IBC } from "./foundry/transaction"; |
| 5 | +import { delay } from "./util"; |
| 6 | +import Debug from "debug"; |
| 7 | + |
| 8 | +const debug = Debug("common:tx"); |
| 9 | + |
| 10 | +export interface ChainConfig { |
| 11 | + /** |
| 12 | + * Example: "http://localhost:8080" |
| 13 | + */ |
| 14 | + server: string; |
| 15 | + networkId: string; |
| 16 | + faucetAddress: PlatformAddress; |
| 17 | +} |
2 | 18 |
|
3 | 19 | export class Chain { |
4 | | - public async sendDatagram(datagram: Datagram): Promise<any> { |
5 | | - return null; |
| 20 | + private readonly sdk: SDK; |
| 21 | + private readonly faucetAddress: PlatformAddress; |
| 22 | + |
| 23 | + public constructor(config: ChainConfig) { |
| 24 | + this.sdk = new SDK({ |
| 25 | + server: config.server, |
| 26 | + networkId: config.networkId |
| 27 | + }); |
| 28 | + this.faucetAddress = config.faucetAddress; |
| 29 | + } |
| 30 | + |
| 31 | + public async sendDatagram(datagram: Datagram): Promise<void> { |
| 32 | + const ibcAction = new IBC(this.sdk.networkId, datagram.rlpBytes()); |
| 33 | + |
| 34 | + const seq = await this.sdk.rpc.chain.getSeq(this.faucetAddress); |
| 35 | + const signedTx = await this.sdk.key.signTransaction(ibcAction, { |
| 36 | + account: this.faucetAddress, |
| 37 | + fee: 100, |
| 38 | + seq |
| 39 | + }); |
| 40 | + |
| 41 | + const txHash = await this.sdk.rpc.chain.sendSignedTransaction(signedTx); |
| 42 | + waitForTx(this.sdk, txHash); |
6 | 43 | } |
7 | 44 | } |
| 45 | + |
| 46 | +async function waitForTx(sdk: SDK, txHash: H256) { |
| 47 | + const timeout = delay(10 * 1000).then(() => { |
| 48 | + throw new Error("Timeout"); |
| 49 | + }); |
| 50 | + const wait = (async () => { |
| 51 | + while (true) { |
| 52 | + debug(`wait tx: ${txHash.toString()}`); |
| 53 | + if (sdk.rpc.chain.containsTransaction(txHash)) { |
| 54 | + return; |
| 55 | + } |
| 56 | + await delay(500); |
| 57 | + } |
| 58 | + })(); |
| 59 | + return Promise.race([timeout, wait]); |
| 60 | +} |
0 commit comments