This repository has been archived by the owner on Feb 13, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 66
/
Copy pathibcclient.ts
1548 lines (1445 loc) · 46.6 KB
/
ibcclient.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { toAscii, toBase64 } from '@cosmjs/encoding';
import { EncodeObject, OfflineSigner, Registry } from '@cosmjs/proto-signing';
import {
AuthExtension,
BankExtension,
calculateFee,
Coin,
defaultRegistryTypes,
GasPrice,
isBroadcastTxFailure,
logs,
QueryClient,
setupAuthExtension,
setupBankExtension,
setupStakingExtension,
SigningStargateClient,
SigningStargateClientOptions,
StakingExtension,
} from '@cosmjs/stargate';
import {
ReadonlyDateWithNanoseconds,
tendermint34,
Tendermint34Client,
} from '@cosmjs/tendermint-rpc';
import { arrayContentEquals, assert, sleep } from '@cosmjs/utils';
import cloneDeep from 'lodash/cloneDeep';
import Long from 'long';
import { Any } from '../codec/google/protobuf/any';
import { MsgTransfer } from '../codec/ibc/applications/transfer/v1/tx';
import { Order, Packet, State } from '../codec/ibc/core/channel/v1/channel';
import {
MsgAcknowledgement,
MsgChannelOpenAck,
MsgChannelOpenConfirm,
MsgChannelOpenInit,
MsgChannelOpenTry,
MsgRecvPacket,
MsgTimeout,
} from '../codec/ibc/core/channel/v1/tx';
import { Height } from '../codec/ibc/core/client/v1/client';
import {
MsgCreateClient,
MsgUpdateClient,
} from '../codec/ibc/core/client/v1/tx';
import { Version } from '../codec/ibc/core/connection/v1/connection';
import {
MsgConnectionOpenAck,
MsgConnectionOpenConfirm,
MsgConnectionOpenInit,
MsgConnectionOpenTry,
} from '../codec/ibc/core/connection/v1/tx';
import {
ClientState as TendermintClientState,
ConsensusState as TendermintConsensusState,
Header as TendermintHeader,
} from '../codec/ibc/lightclients/tendermint/v1/tendermint';
import {
blockIDFlagFromJSON,
Commit,
Header,
SignedHeader,
} from '../codec/tendermint/types/types';
import { ValidatorSet } from '../codec/tendermint/types/validator';
import { Logger, NoopLogger } from './logger';
import { IbcExtension, setupIbcExtension } from './queries/ibc';
import {
Ack,
buildClientState,
buildConsensusState,
createBroadcastTxErrorMessage,
mapRpcPubKeyToProto,
parseRevisionNumber,
presentPacketData,
subtractBlock,
timestampFromDateNanos,
toIntHeight,
} from './utils';
function deepCloneAndMutate<T extends Record<string, unknown>>(
object: T,
mutateFn: (deepClonedObject: T) => void
): Record<string, unknown> {
const deepClonedObject = cloneDeep(object);
mutateFn(deepClonedObject);
return deepClonedObject;
}
function toBase64AsAny(...input: Parameters<typeof toBase64>) {
return toBase64(...input) as any; // eslint-disable-line @typescript-eslint/no-explicit-any
}
/**** These are needed to bootstrap the endpoints */
/* Some of them are hardcoded various places, which should we make configurable? */
// const DefaultTrustLevel = '1/3';
// const MaxClockDrift = 10; // 10 seconds
// const upgradePath = ['upgrade', 'upgradedIBCState'];
// const allowUpgradeAfterExpiry = false;
// const allowUpgradeAfterMisbehavior = false;
// these are from the cosmos sdk implementation
const defaultMerklePrefix = {
keyPrefix: toAscii('ibc'),
};
const defaultConnectionVersion: Version = {
identifier: '1',
features: ['ORDER_ORDERED', 'ORDER_UNORDERED'],
};
// this is a sane default, but we can revisit it
const defaultDelayPeriod = Long.ZERO;
function ibcRegistry(): Registry {
return new Registry([
...defaultRegistryTypes,
['/ibc.core.client.v1.MsgCreateClient', MsgCreateClient],
['/ibc.core.client.v1.MsgUpdateClient', MsgUpdateClient],
['/ibc.core.connection.v1.MsgConnectionOpenInit', MsgConnectionOpenInit],
['/ibc.core.connection.v1.MsgConnectionOpenTry', MsgConnectionOpenTry],
['/ibc.core.connection.v1.MsgConnectionOpenAck', MsgConnectionOpenAck],
[
'/ibc.core.connection.v1.MsgConnectionOpenConfirm',
MsgConnectionOpenConfirm,
],
['/ibc.core.channel.v1.MsgChannelOpenInit', MsgChannelOpenInit],
['/ibc.core.channel.v1.MsgChannelOpenTry', MsgChannelOpenTry],
['/ibc.core.channel.v1.MsgChannelOpenAck', MsgChannelOpenAck],
['/ibc.core.channel.v1.MsgChannelOpenConfirm', MsgChannelOpenConfirm],
['/ibc.core.channel.v1.MsgRecvPacket', MsgRecvPacket],
['/ibc.core.channel.v1.MsgAcknowledgement', MsgAcknowledgement],
['/ibc.core.channel.v1.MsgTimeout', MsgTimeout],
['/ibc.applications.transfer.v1.MsgTransfer', MsgTransfer],
]);
}
/// This is the default message result with no extra data
export interface MsgResult {
readonly logs: readonly logs.Log[];
/** Transaction hash (might be used as transaction ID). Guaranteed to be non-empty upper-case hex */
readonly transactionHash: string;
/** block height where this transaction was committed - only set if we send 'block' mode */
readonly height: number;
}
export type CreateClientResult = MsgResult & {
readonly clientId: string;
};
export type CreateConnectionResult = MsgResult & {
readonly connectionId: string;
};
export type CreateChannelResult = MsgResult & {
readonly channelId: string;
};
interface ConnectionHandshakeProof {
clientId: string;
connectionId: string;
clientState?: Any;
proofHeight: Height;
// proof of the state of the connection on remote chain
proofConnection: Uint8Array;
// proof of client state included in message
proofClient: Uint8Array;
// proof of client consensus state
proofConsensus: Uint8Array;
// last header height of this chain known by the remote chain
consensusHeight?: Height;
}
export interface ChannelHandshake {
id: ChannelInfo;
proofHeight: Height;
// proof of the state of the channel on remote chain
proof: Uint8Array;
}
export interface ChannelInfo {
readonly portId: string;
readonly channelId: string;
}
export interface IbcGasLimits {
readonly bankSend: number;
readonly initClient: number;
readonly updateClient: number;
readonly initConnection: number;
readonly connectionHandshake: number;
readonly initChannel: number;
readonly channelHandshake: number;
readonly receivePacket: number;
readonly ackPacket: number;
readonly timeoutPacket: number;
readonly transfer: number;
}
export type IbcClientOptions = SigningStargateClientOptions & {
gasLimits?: Partial<IbcGasLimits>;
logger?: Logger;
gasPrice?: GasPrice;
};
const defaultGasPrice = GasPrice.fromString('0.025ucosm');
const defaultGasLimits: IbcGasLimits = {
bankSend: 200000,
initClient: 150000,
updateClient: 600000,
initConnection: 150000,
connectionHandshake: 300000,
initChannel: 150000,
channelHandshake: 300000,
receivePacket: 300000,
ackPacket: 300000,
timeoutPacket: 300000,
transfer: 180000,
};
export class IbcClient {
public readonly gasPrice: GasPrice;
public readonly limits: IbcGasLimits;
public readonly sign: SigningStargateClient;
public readonly query: QueryClient &
AuthExtension &
BankExtension &
IbcExtension &
StakingExtension;
public readonly tm: Tendermint34Client;
public readonly senderAddress: string;
public readonly logger: Logger;
public readonly chainId: string;
public readonly revisionNumber: Long;
public static async connectWithSigner(
endpoint: string,
signer: OfflineSigner,
senderAddress: string,
options: IbcClientOptions = {}
): Promise<IbcClient> {
// override any registry setup, use the other options
const mergedOptions = {
...options,
registry: ibcRegistry(),
};
const signingClient = await SigningStargateClient.connectWithSigner(
endpoint,
signer,
mergedOptions
);
const tmClient = await Tendermint34Client.connect(endpoint);
const chainId = await signingClient.getChainId();
return new IbcClient(
signingClient,
tmClient,
senderAddress,
chainId,
options
);
}
private constructor(
signingClient: SigningStargateClient,
tmClient: Tendermint34Client,
senderAddress: string,
chainId: string,
options: IbcClientOptions
) {
this.sign = signingClient;
this.tm = tmClient;
this.query = QueryClient.withExtensions(
tmClient,
setupAuthExtension,
setupBankExtension,
setupIbcExtension,
setupStakingExtension
);
this.senderAddress = senderAddress;
this.chainId = chainId;
this.revisionNumber = parseRevisionNumber(chainId);
const { gasPrice = defaultGasPrice, gasLimits = {}, logger } = options;
this.gasPrice = gasPrice;
// we must do this explicitly, not
// this.limits = { ...defaultGasLimits, ...gasLimits };
// so undefined in gasLimits don't overwrite defaults
this.limits = {
bankSend: gasLimits.bankSend || defaultGasLimits.bankSend,
initClient: gasLimits.initClient || defaultGasLimits.initClient,
updateClient: gasLimits.updateClient || defaultGasLimits.updateClient,
initConnection:
gasLimits.initConnection || defaultGasLimits.initConnection,
connectionHandshake:
gasLimits.connectionHandshake || defaultGasLimits.connectionHandshake,
initChannel: gasLimits.initChannel || defaultGasLimits.initChannel,
channelHandshake:
gasLimits.channelHandshake || defaultGasLimits.channelHandshake,
receivePacket: gasLimits.receivePacket || defaultGasLimits.receivePacket,
ackPacket: gasLimits.ackPacket || defaultGasLimits.ackPacket,
timeoutPacket: gasLimits.timeoutPacket || defaultGasLimits.timeoutPacket,
transfer: gasLimits.transfer || defaultGasLimits.transfer,
};
this.logger = logger ?? new NoopLogger();
}
public revisionHeight(height: number): Height {
return Height.fromPartial({
revisionHeight: Long.fromNumber(height),
revisionNumber: this.revisionNumber,
});
}
public ensureRevisionHeight(height: number | Height): Height {
if (typeof height === 'number') {
return Height.fromPartial({
revisionHeight: Long.fromNumber(height),
revisionNumber: this.revisionNumber,
});
}
if (height.revisionNumber.toNumber() !== this.revisionNumber.toNumber()) {
throw new Error(
`Using incorrect revisionNumber ${height.revisionNumber} on chain with ${this.revisionNumber}`
);
}
return height;
}
public async timeoutHeight(blocksInFuture: number): Promise<Height> {
const header = await this.latestHeader();
return this.revisionHeight(header.height + blocksInFuture);
}
public getChainId(): Promise<string> {
this.logger.verbose('Get chain ID');
return this.sign.getChainId();
}
public async header(height: number): Promise<tendermint34.Header> {
this.logger.verbose(`Get header for height ${height}`);
// TODO: expose header method on tmClient and use that
const resp = await this.tm.blockchain(height, height);
return resp.blockMetas[0].header;
}
public async latestHeader(): Promise<tendermint34.Header> {
// TODO: expose header method on tmClient and use that
const block = await this.tm.block();
return block.block.header;
}
public async currentTime(): Promise<ReadonlyDateWithNanoseconds> {
// const status = await this.tm.status();
// return status.syncInfo.latestBlockTime;
return (await this.latestHeader()).time;
}
public async currentHeight(): Promise<number> {
const status = await this.tm.status();
return status.syncInfo.latestBlockHeight;
}
public async currentRevision(): Promise<Height> {
const block = await this.currentHeight();
return this.revisionHeight(block);
}
public async waitOneBlock(): Promise<void> {
// ensure this works
const start = await this.currentHeight();
let end: number;
do {
await sleep(500);
end = await this.currentHeight();
} while (end === start);
// TODO: this works but only for websocket connections, is there some code that falls back to polling in cosmjs?
// await firstEvent(this.tm.subscribeNewBlockHeader());
}
// we may have to wait a bit before a tx returns and making queries on the event log
public async waitForIndexer(): Promise<void> {
await sleep(50);
}
public getCommit(height?: number): Promise<tendermint34.CommitResponse> {
this.logger.verbose(
height === undefined
? 'Get latest commit'
: `Get commit for height ${height}`
);
return this.tm.commit(height);
}
/** Returns the unbonding period in seconds */
public async getUnbondingPeriod(): Promise<number> {
const { params } = await this.query.staking.params();
const seconds = params?.unbondingTime?.seconds?.toNumber();
if (!seconds) {
throw new Error('No unbonding period found');
}
this.logger.verbose('Queried unbonding period', { seconds });
return seconds;
}
public async getSignedHeader(height?: number): Promise<SignedHeader> {
const { header: rpcHeader, commit: rpcCommit } = await this.getCommit(
height
);
const header = Header.fromPartial({
...rpcHeader,
version: {
block: Long.fromNumber(rpcHeader.version.block),
},
height: Long.fromNumber(rpcHeader.height),
time: timestampFromDateNanos(rpcHeader.time),
lastBlockId: {
hash: rpcHeader.lastBlockId?.hash,
partSetHeader: rpcHeader.lastBlockId?.parts,
},
});
const signatures = rpcCommit.signatures.map((sig) => ({
...sig,
timestamp: sig.timestamp && timestampFromDateNanos(sig.timestamp),
blockIdFlag: blockIDFlagFromJSON(sig.blockIdFlag),
}));
const commit = Commit.fromPartial({
height: Long.fromNumber(rpcCommit.height),
round: rpcCommit.round,
blockId: {
hash: rpcCommit.blockId.hash,
partSetHeader: rpcCommit.blockId.parts,
},
signatures,
});
// For the vote sign bytes, it checks (from the commit):
// Height, Round, BlockId, TimeStamp, ChainID
return { header, commit };
}
public async getValidatorSet(height: number): Promise<ValidatorSet> {
this.logger.verbose(`Get validator set for height ${height}`);
// we need to query the header to find out who the proposer was, and pull them out
const { proposerAddress } = await this.header(height);
const validators = await this.tm.validatorsAll(height);
const mappedValidators = validators.validators.map((val) => ({
address: val.address,
pubKey: mapRpcPubKeyToProto(val.pubkey),
votingPower: Long.fromNumber(val.votingPower),
proposerPriority: val.proposerPriority
? Long.fromNumber(val.proposerPriority)
: undefined,
}));
const totalPower = validators.validators.reduce(
(x, v) => x + v.votingPower,
0
);
const proposer = mappedValidators.find((val) =>
arrayContentEquals(val.address, proposerAddress)
);
return ValidatorSet.fromPartial({
validators: mappedValidators,
totalVotingPower: Long.fromNumber(totalPower),
proposer,
});
}
// this builds a header to update a remote client.
// you must pass the last known height on the remote side so we can properly generate it.
// it will update to the latest state of this chain.
//
// This is the logic that validates the returned struct:
// ibc check: /~https://github.com/cosmos/cosmos-sdk/blob/v0.41.0/x/ibc/light-clients/07-tendermint/types/update.go#L87-L167
// tendermint check: /~https://github.com/tendermint/tendermint/blob/v0.34.3/light/verifier.go#L19-L79
// sign bytes: /~https://github.com/tendermint/tendermint/blob/v0.34.3/types/validator_set.go#L762-L821
// * /~https://github.com/tendermint/tendermint/blob/v0.34.3/types/validator_set.go#L807-L810
// * /~https://github.com/tendermint/tendermint/blob/v0.34.3/types/block.go#L780-L809
// * /~https://github.com/tendermint/tendermint/blob/bf9e36d02d2eb22f6fe8961d0d7d3d34307ba38e/types/canonical.go#L54-L65
//
// For the vote sign bytes, it checks (from the commit):
// Height, Round, BlockId, TimeStamp, ChainID
public async buildHeader(lastHeight: number): Promise<TendermintHeader> {
const signedHeader = await this.getSignedHeader();
// "assert that trustedVals is NextValidators of last trusted header"
// /~https://github.com/cosmos/cosmos-sdk/blob/v0.41.0/x/ibc/light-clients/07-tendermint/types/update.go#L74
const validatorHeight = lastHeight + 1;
/* eslint @typescript-eslint/no-non-null-assertion: "off" */
const curHeight = signedHeader.header!.height.toNumber();
return TendermintHeader.fromPartial({
signedHeader,
validatorSet: await this.getValidatorSet(curHeight),
trustedHeight: this.revisionHeight(lastHeight),
trustedValidators: await this.getValidatorSet(validatorHeight),
});
}
// trustedHeight must be proven by the client on the destination chain
// and include a proof for the connOpenInit (eg. must be 1 or more blocks after the
// block connOpenInit Tx was in).
//
// pass a header height that was previously updated to on the remote chain using updateClient.
// note: the queries will be for the block before this header, so the proofs match up (appHash is on H+1)
public async getConnectionProof(
clientId: string,
connectionId: string,
headerHeight: Height | number
): Promise<ConnectionHandshakeProof> {
const proofHeight = this.ensureRevisionHeight(headerHeight);
const queryHeight = subtractBlock(proofHeight, 1);
const {
clientState,
proof: proofClient,
// proofHeight,
} = await this.query.ibc.proof.client.state(clientId, queryHeight);
// This is the most recent state we have on this chain of the other
const { latestHeight: consensusHeight } =
await this.query.ibc.client.stateTm(clientId);
assert(consensusHeight);
// get the init proof
const { proof: proofConnection } =
await this.query.ibc.proof.connection.connection(
connectionId,
queryHeight
);
// get the consensus proof
const { proof: proofConsensus } =
await this.query.ibc.proof.client.consensusState(
clientId,
consensusHeight,
queryHeight
);
return {
clientId,
clientState,
connectionId,
proofHeight,
proofConnection,
proofClient,
proofConsensus,
consensusHeight,
};
}
// trustedHeight must be proven by the client on the destination chain
// and include a proof for the connOpenInit (eg. must be 1 or more blocks after the
// block connOpenInit Tx was in).
//
// pass a header height that was previously updated to on the remote chain using updateClient.
// note: the queries will be for the block before this header, so the proofs match up (appHash is on H+1)
public async getChannelProof(
id: ChannelInfo,
headerHeight: Height | number
): Promise<ChannelHandshake> {
const proofHeight = this.ensureRevisionHeight(headerHeight);
const queryHeight = subtractBlock(proofHeight, 1);
const { proof } = await this.query.ibc.proof.channel.channel(
id.portId,
id.channelId,
queryHeight
);
return {
id,
proofHeight,
proof,
};
}
public async getPacketProof(
packet: Packet,
headerHeight: Height | number
): Promise<Uint8Array> {
const proofHeight = this.ensureRevisionHeight(headerHeight);
const queryHeight = subtractBlock(proofHeight, 1);
const { proof } = await this.query.ibc.proof.channel.packetCommitment(
packet.sourcePort,
packet.sourceChannel,
packet.sequence,
queryHeight
);
return proof;
}
public async getAckProof(
{ originalPacket }: Ack,
headerHeight: Height | number
): Promise<Uint8Array> {
const proofHeight = this.ensureRevisionHeight(headerHeight);
const queryHeight = subtractBlock(proofHeight, 1);
const res = await this.query.ibc.proof.channel.packetAcknowledgement(
originalPacket.destinationPort,
originalPacket.destinationChannel,
originalPacket.sequence.toNumber(),
queryHeight
);
const { proof } = res;
return proof;
}
public async getTimeoutProof(
{ originalPacket }: Ack,
headerHeight: Height | number
): Promise<Uint8Array> {
const proofHeight = this.ensureRevisionHeight(headerHeight);
const queryHeight = subtractBlock(proofHeight, 1);
const proof = await this.query.ibc.proof.channel.receiptProof(
originalPacket.destinationPort,
originalPacket.destinationChannel,
originalPacket.sequence.toNumber(),
queryHeight
);
return proof;
}
/*
These are helpers to query, build data and submit a message
Currently all prefixed with doXxx, but please look for better naming
*/
// Updates existing client on this chain with data from src chain.
// Returns the height that was updated to.
public async doUpdateClient(
clientId: string,
src: IbcClient
): Promise<Height> {
const { latestHeight } = await this.query.ibc.client.stateTm(clientId);
const header = await src.buildHeader(toIntHeight(latestHeight));
await this.updateTendermintClient(clientId, header);
const height = header.signedHeader?.header?.height?.toNumber() ?? 0;
return src.revisionHeight(height);
}
/***** These are all direct wrappers around message constructors ********/
public async sendTokens(
recipientAddress: string,
transferAmount: readonly Coin[],
memo?: string
): Promise<MsgResult> {
this.logger.verbose(`Send tokens to ${recipientAddress}`);
this.logger.debug('Send tokens:', {
senderAddress: this.senderAddress,
recipientAddress,
transferAmount,
memo,
});
const result = await this.sign.sendTokens(
this.senderAddress,
recipientAddress,
transferAmount,
calculateFee(this.limits.bankSend, this.gasPrice),
memo
);
if (isBroadcastTxFailure(result)) {
throw new Error(createBroadcastTxErrorMessage(result));
}
const parsedLogs = logs.parseRawLog(result.rawLog);
return {
logs: parsedLogs,
transactionHash: result.transactionHash,
height: result.height,
};
}
/* Send any number of messages, you are responsible for encoding them */
public async sendMultiMsg(
msgs: EncodeObject[],
gasLimit: number
): Promise<MsgResult> {
this.logger.verbose(`Broadcast multiple msgs`);
this.logger.debug(`Multiple msgs:`, {
msgs,
gasLimit,
});
const senderAddress = this.senderAddress;
const fee = calculateFee(gasLimit, this.gasPrice);
const result = await this.sign.signAndBroadcast(senderAddress, msgs, fee);
if (isBroadcastTxFailure(result)) {
throw new Error(createBroadcastTxErrorMessage(result));
}
const parsedLogs = logs.parseRawLog(result.rawLog);
return {
logs: parsedLogs,
transactionHash: result.transactionHash,
height: result.height,
};
}
public async createTendermintClient(
clientState: TendermintClientState,
consensusState: TendermintConsensusState
): Promise<CreateClientResult> {
this.logger.verbose(`Create Tendermint client`);
const senderAddress = this.senderAddress;
const createMsg = {
typeUrl: '/ibc.core.client.v1.MsgCreateClient',
value: MsgCreateClient.fromPartial({
signer: senderAddress,
clientState: {
typeUrl: '/ibc.lightclients.tendermint.v1.ClientState',
value: TendermintClientState.encode(clientState).finish(),
},
consensusState: {
typeUrl: '/ibc.lightclients.tendermint.v1.ConsensusState',
value: TendermintConsensusState.encode(consensusState).finish(),
},
}),
};
this.logger.debug('MsgCreateClient', createMsg);
const result = await this.sign.signAndBroadcast(
senderAddress,
[createMsg],
calculateFee(this.limits.initClient, this.gasPrice)
);
if (isBroadcastTxFailure(result)) {
throw new Error(createBroadcastTxErrorMessage(result));
}
const parsedLogs = logs.parseRawLog(result.rawLog);
const clientId = logs.findAttribute(
parsedLogs,
'create_client',
'client_id'
).value;
return {
logs: parsedLogs,
transactionHash: result.transactionHash,
height: result.height,
clientId,
};
}
public async updateTendermintClient(
clientId: string,
header: TendermintHeader
): Promise<MsgResult> {
this.logger.verbose(`Update Tendermint client ${clientId}`);
const senderAddress = this.senderAddress;
const updateMsg = {
typeUrl: '/ibc.core.client.v1.MsgUpdateClient',
value: MsgUpdateClient.fromPartial({
signer: senderAddress,
clientId,
header: {
typeUrl: '/ibc.lightclients.tendermint.v1.Header',
value: TendermintHeader.encode(header).finish(),
},
}),
};
this.logger.debug(
`MsgUpdateClient`,
deepCloneAndMutate(updateMsg, (mutableMsg) => {
if (mutableMsg.value.header?.value) {
mutableMsg.value.header.value = toBase64AsAny(
mutableMsg.value.header.value
);
}
})
);
const result = await this.sign.signAndBroadcast(
senderAddress,
[updateMsg],
calculateFee(this.limits.updateClient, this.gasPrice)
);
if (isBroadcastTxFailure(result)) {
throw new Error(createBroadcastTxErrorMessage(result));
}
const parsedLogs = logs.parseRawLog(result.rawLog);
return {
logs: parsedLogs,
transactionHash: result.transactionHash,
height: result.height,
};
}
public async connOpenInit(
clientId: string,
remoteClientId: string
): Promise<CreateConnectionResult> {
this.logger.info(`Connection open init: ${clientId} => ${remoteClientId}`);
const senderAddress = this.senderAddress;
const msg = {
typeUrl: '/ibc.core.connection.v1.MsgConnectionOpenInit',
value: MsgConnectionOpenInit.fromPartial({
clientId,
counterparty: {
clientId: remoteClientId,
prefix: defaultMerklePrefix,
},
version: defaultConnectionVersion,
delayPeriod: defaultDelayPeriod,
signer: senderAddress,
}),
};
this.logger.debug(`MsgConnectionOpenInit`, msg);
const result = await this.sign.signAndBroadcast(
senderAddress,
[msg],
calculateFee(this.limits.initConnection, this.gasPrice)
);
if (isBroadcastTxFailure(result)) {
throw new Error(createBroadcastTxErrorMessage(result));
}
const parsedLogs = logs.parseRawLog(result.rawLog);
const connectionId = logs.findAttribute(
parsedLogs,
'connection_open_init',
'connection_id'
).value;
this.logger.debug(`Connection open init successful: ${connectionId}`);
return {
logs: parsedLogs,
transactionHash: result.transactionHash,
height: result.height,
connectionId,
};
}
public async connOpenTry(
myClientId: string,
proof: ConnectionHandshakeProof
): Promise<CreateConnectionResult> {
this.logger.info(
`Connection open try: ${myClientId} => ${proof.clientId} (${proof.connectionId})`
);
const senderAddress = this.senderAddress;
const {
clientId,
connectionId,
clientState,
proofHeight,
proofConnection: proofInit,
proofClient,
proofConsensus,
consensusHeight,
} = proof;
const msg = {
typeUrl: '/ibc.core.connection.v1.MsgConnectionOpenTry',
value: MsgConnectionOpenTry.fromPartial({
clientId: myClientId,
counterparty: {
clientId,
connectionId,
prefix: defaultMerklePrefix,
},
delayPeriod: defaultDelayPeriod,
counterpartyVersions: [defaultConnectionVersion],
signer: senderAddress,
clientState,
proofHeight,
proofInit,
proofClient,
proofConsensus,
consensusHeight,
}),
};
this.logger.debug(
'MsgConnectionOpenTry',
deepCloneAndMutate(msg, (mutableMsg) => {
mutableMsg.value.proofClient = toBase64AsAny(
mutableMsg.value.proofClient
);
mutableMsg.value.proofConsensus = toBase64AsAny(
mutableMsg.value.proofConsensus
);
mutableMsg.value.proofInit = toBase64AsAny(mutableMsg.value.proofInit);
})
);
const result = await this.sign.signAndBroadcast(
senderAddress,
[msg],
calculateFee(this.limits.connectionHandshake, this.gasPrice)
);
if (isBroadcastTxFailure(result)) {
throw new Error(createBroadcastTxErrorMessage(result));
}
const parsedLogs = logs.parseRawLog(result.rawLog);
const myConnectionId = logs.findAttribute(
parsedLogs,
'connection_open_try',
'connection_id'
).value;
this.logger.debug(
`Connection open try successful: ${myConnectionId} => ${connectionId}`
);
return {
logs: parsedLogs,
transactionHash: result.transactionHash,
height: result.height,
connectionId: myConnectionId,
};
}
public async connOpenAck(
myConnectionId: string,
proof: ConnectionHandshakeProof
): Promise<MsgResult> {
this.logger.info(
`Connection open ack: ${myConnectionId} => ${proof.connectionId}`
);
const senderAddress = this.senderAddress;
const {
connectionId,
clientState,
proofHeight,
proofConnection: proofTry,
proofClient,
proofConsensus,
consensusHeight,
} = proof;
const msg = {
typeUrl: '/ibc.core.connection.v1.MsgConnectionOpenAck',
value: MsgConnectionOpenAck.fromPartial({
connectionId: myConnectionId,
counterpartyConnectionId: connectionId,
version: defaultConnectionVersion,
signer: senderAddress,
clientState,
proofHeight,
proofTry,
proofClient,
proofConsensus,
consensusHeight,
}),
};
this.logger.debug(
'MsgConnectionOpenAck',
deepCloneAndMutate(msg, (mutableMsg) => {
mutableMsg.value.proofConsensus = toBase64AsAny(
mutableMsg.value.proofConsensus
);
mutableMsg.value.proofTry = toBase64AsAny(mutableMsg.value.proofTry);
mutableMsg.value.proofClient = toBase64AsAny(
mutableMsg.value.proofClient
);
})
);
const result = await this.sign.signAndBroadcast(
senderAddress,
[msg],
calculateFee(this.limits.connectionHandshake, this.gasPrice)
);
if (isBroadcastTxFailure(result)) {
throw new Error(createBroadcastTxErrorMessage(result));
}
const parsedLogs = logs.parseRawLog(result.rawLog);
return {
logs: parsedLogs,
transactionHash: result.transactionHash,
height: result.height,
};
}
public async connOpenConfirm(
myConnectionId: string,
proof: ConnectionHandshakeProof
): Promise<MsgResult> {
this.logger.info(`Connection open confirm: ${myConnectionId}`);
const senderAddress = this.senderAddress;
const { proofHeight, proofConnection: proofAck } = proof;
const msg = {
typeUrl: '/ibc.core.connection.v1.MsgConnectionOpenConfirm',
value: MsgConnectionOpenConfirm.fromPartial({
connectionId: myConnectionId,
signer: senderAddress,
proofHeight,
proofAck,
}),
};
this.logger.debug(
'MsgConnectionOpenConfirm',
deepCloneAndMutate(msg, (mutableMsg) => {
mutableMsg.value.proofAck = toBase64AsAny(mutableMsg.value.proofAck);
})
);
const result = await this.sign.signAndBroadcast(
senderAddress,
[msg],
calculateFee(this.limits.connectionHandshake, this.gasPrice)
);
if (isBroadcastTxFailure(result)) {
throw new Error(createBroadcastTxErrorMessage(result));