-
Notifications
You must be signed in to change notification settings - Fork 579
Expand file tree
/
Copy pathprocessor.rs
More file actions
979 lines (854 loc) · 36.5 KB
/
processor.rs
File metadata and controls
979 lines (854 loc) · 36.5 KB
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
//! Processor logic shared by all Hyperlane Sealevel Token programs.
use access_control::AccessControl;
use account_utils::{create_pda_account, SizedData};
use borsh::{BorshDeserialize, BorshSerialize};
use hyperlane_core::{Decode, Encode, H256, U256};
use hyperlane_sealevel_connection_client::{
gas_router::{GasRouterConfig, HyperlaneGasRouter, HyperlaneGasRouterAccessControl},
router::{
HyperlaneRouter, HyperlaneRouterAccessControl, HyperlaneRouterMessageRecipient,
RemoteRouterConfig,
},
HyperlaneConnectionClient, HyperlaneConnectionClientSetterAccessControl,
};
use hyperlane_sealevel_igp::{
accounts::InterchainGasPaymasterType,
instruction::{Instruction as IgpInstruction, PayForGas as IgpPayForGas},
};
use hyperlane_sealevel_mailbox::{
instruction::{Instruction as MailboxInstruction, OutboxDispatch as MailboxOutboxDispatch},
mailbox_message_dispatch_authority_pda_seeds, mailbox_process_authority_pda_seeds,
};
use hyperlane_sealevel_message_recipient_interface::HandleInstruction;
use hyperlane_warp_route::TokenMessage;
use serializable_account_meta::{SerializableAccountMeta, SimulationReturnData};
use solana_program::{
account_info::{next_account_info, AccountInfo},
entrypoint::ProgramResult,
instruction::{AccountMeta, Instruction},
msg,
program::{get_return_data, invoke, invoke_signed, set_return_data},
program_error::ProgramError,
pubkey::Pubkey,
rent::Rent,
sysvar::Sysvar,
};
use solana_system_interface::program as system_program;
use std::collections::HashMap;
use crate::{
accounts::{HyperlaneToken, HyperlaneTokenAccount},
error::Error,
instruction::{Init, TransferRemote},
};
/// Seeds relating to the PDA account with information about this warp route.
/// For convenience in getting the account metas required for handling messages,
/// this is the same as the `HANDLE_ACCOUNT_METAS_PDA_SEEDS` in the message
/// recipient interface.
#[macro_export]
macro_rules! hyperlane_token_pda_seeds {
() => {{
&[
b"hyperlane_message_recipient",
b"-",
b"handle",
b"-",
b"account_metas",
]
}};
($bump_seed:expr) => {{
&[
b"hyperlane_message_recipient",
b"-",
b"handle",
b"-",
b"account_metas",
&[$bump_seed],
]
}};
}
/// A plugin that handles token transfers for a Hyperlane Sealevel Token program.
pub trait HyperlaneSealevelTokenPlugin
where
Self: BorshSerialize
+ BorshDeserialize
+ std::cmp::PartialEq
+ std::fmt::Debug
+ Default
+ Sized
+ SizedData,
{
/// Initializes the plugin.
fn initialize<'a, 'b>(
program_id: &Pubkey,
system_program: &'a AccountInfo<'b>,
token_account: &'a AccountInfo<'b>,
payer_account: &'a AccountInfo<'b>,
accounts_iter: &mut std::slice::Iter<'a, AccountInfo<'b>>,
) -> Result<Self, ProgramError>;
/// Transfers tokens into the program.
fn transfer_in<'a, 'b>(
program_id: &Pubkey,
token: &HyperlaneToken<Self>,
sender_wallet: &'a AccountInfo<'b>,
accounts_iter: &mut std::slice::Iter<'a, AccountInfo<'b>>,
amount: u64,
) -> Result<(), ProgramError>;
/// Transfers tokens out of the program.
fn transfer_out<'a, 'b>(
program_id: &Pubkey,
token: &HyperlaneToken<Self>,
system_program: &'a AccountInfo<'b>,
recipient_wallet: &'a AccountInfo<'b>,
accounts_iter: &mut std::slice::Iter<'a, AccountInfo<'b>>,
amount: u64,
) -> Result<(), ProgramError>;
/// Gets the AccountMetas required by the `transfer_out` function.
/// Returns (AccountMetas, whether recipient wallet must be writeable)
fn transfer_out_account_metas(
program_id: &Pubkey,
token: &HyperlaneToken<Self>,
token_message: &TokenMessage,
) -> Result<(Vec<SerializableAccountMeta>, bool), ProgramError>;
}
/// Core functionality of a Hyperlane Sealevel Token program that uses
/// a plugin to handle token transfers.
pub struct HyperlaneSealevelToken<
T: HyperlaneSealevelTokenPlugin
+ BorshDeserialize
+ BorshSerialize
+ std::cmp::PartialEq
+ std::fmt::Debug,
> {
_plugin: std::marker::PhantomData<T>,
}
impl<T> HyperlaneSealevelToken<T>
where
T: HyperlaneSealevelTokenPlugin
+ BorshSerialize
+ BorshDeserialize
+ std::cmp::PartialEq
+ std::fmt::Debug
+ Default,
{
/// Initializes the program.
///
/// Accounts:
/// - 0: `[executable]` The system program.
/// - 1: `[writable]` The token PDA account.
/// - 2: `[writable]` The dispatch authority PDA account.
/// - 3: `[signer]` The payer and access control owner.
/// - 4..N: `[??..??]` Plugin-specific accounts.
pub fn initialize(program_id: &Pubkey, accounts: &[AccountInfo], init: Init) -> ProgramResult {
let accounts_iter = &mut accounts.iter();
// Account 0: System program
let system_program_id = system_program::ID;
let system_program = next_account_info(accounts_iter)?;
if system_program.key != &system_program_id {
return Err(ProgramError::IncorrectProgramId);
}
// Account 1: Token storage account
let token_account = next_account_info(accounts_iter)?;
let (token_key, token_bump) =
Pubkey::find_program_address(hyperlane_token_pda_seeds!(), program_id);
if &token_key != token_account.key {
return Err(ProgramError::IncorrectProgramId);
}
if !token_account.data_is_empty() || token_account.owner != &system_program_id {
return Err(ProgramError::AccountAlreadyInitialized);
}
// Account 2: Dispatch authority PDA.
let dispatch_authority_account = next_account_info(accounts_iter)?;
let (dispatch_authority_key, dispatch_authority_bump) = Pubkey::find_program_address(
mailbox_message_dispatch_authority_pda_seeds!(),
program_id,
);
if *dispatch_authority_account.key != dispatch_authority_key {
return Err(ProgramError::IncorrectProgramId);
}
if !dispatch_authority_account.data_is_empty()
|| dispatch_authority_account.owner != &system_program_id
{
return Err(ProgramError::AccountAlreadyInitialized);
}
// Account 3: Payer
let payer_account = next_account_info(accounts_iter)?;
if !payer_account.is_signer {
return Err(ProgramError::MissingRequiredSignature);
}
// Get the Mailbox's process authority that is specific to this program
// as a recipient.
let (mailbox_process_authority, _mailbox_process_authority_bump) =
Pubkey::find_program_address(
mailbox_process_authority_pda_seeds!(program_id),
&init.mailbox,
);
let plugin_data = T::initialize(
program_id,
system_program,
token_account,
payer_account,
accounts_iter,
)?;
if accounts_iter.next().is_some() {
return Err(ProgramError::from(Error::ExtraneousAccount));
}
let rent = Rent::get()?;
let token: HyperlaneToken<T> = HyperlaneToken {
bump: token_bump,
mailbox: init.mailbox,
mailbox_process_authority,
dispatch_authority_bump,
owner: Some(*payer_account.key),
interchain_security_module: init.interchain_security_module,
interchain_gas_paymaster: init.interchain_gas_paymaster,
destination_gas: HashMap::new(),
decimals: init.decimals,
remote_decimals: init.remote_decimals,
remote_routers: HashMap::new(),
plugin_data,
};
let token_account_data = HyperlaneTokenAccount::<T>::from(token);
// Create token account PDA
create_pda_account(
payer_account,
&rent,
token_account_data.size(),
program_id,
system_program,
token_account,
hyperlane_token_pda_seeds!(token_bump),
)?;
// Create dispatch authority PDA
create_pda_account(
payer_account,
&rent,
0,
program_id,
system_program,
dispatch_authority_account,
mailbox_message_dispatch_authority_pda_seeds!(dispatch_authority_bump),
)?;
token_account_data.store(token_account, false)?;
Ok(())
}
/// Transfers tokens to a remote.
/// Calls the plugin's `transfer_in` function to transfer tokens in,
/// then dispatches a message to the remote recipient.
///
/// Accounts:
/// - 0: `[executable]` The system program.
/// - 1: `[executable]` The spl_noop program.
/// - 2: `[]` The token PDA account.
/// - 3: `[executable]` The mailbox program.
/// - 4: `[writeable]` The mailbox outbox account.
/// - 5: `[]` Message dispatch authority.
/// - 6: `[signer]` The token sender and mailbox payer.
/// - 7: `[signer]` Unique message / gas payment account.
/// - 8: `[writeable]` Message storage PDA.
/// ---- If using an IGP ----
/// - 9: `[executable]` The IGP program.
/// - 10: `[writeable]` The IGP program data.
/// - 11: `[writeable]` Gas payment PDA.
/// - 12: `[]` OPTIONAL - The Overhead IGP program, if the configured IGP is an Overhead IGP.
/// - 13: `[writeable]` The IGP account.
/// ---- End if ----
/// - 14..N: `[??..??]` Plugin-specific accounts.
pub fn transfer_remote(
program_id: &Pubkey,
accounts: &[AccountInfo],
xfer: TransferRemote,
) -> ProgramResult {
let accounts_iter = &mut accounts.iter();
// Account 0: System program.
let system_program_account = next_account_info(accounts_iter)?;
if system_program_account.key != &system_program::ID {
return Err(ProgramError::InvalidArgument);
}
// Account 1: SPL Noop.
let spl_noop = next_account_info(accounts_iter)?;
if spl_noop.key != &account_utils::SPL_NOOP_PROGRAM_ID {
return Err(ProgramError::InvalidArgument);
}
// Account 2: Token storage account
let token_account = next_account_info(accounts_iter)?;
let token =
HyperlaneTokenAccount::fetch(&mut &token_account.data.borrow()[..])?.into_inner();
let token_seeds: &[&[u8]] = hyperlane_token_pda_seeds!(token.bump);
let expected_token_key = Pubkey::create_program_address(token_seeds, program_id)?;
if token_account.key != &expected_token_key {
return Err(ProgramError::InvalidArgument);
}
if token_account.owner != program_id {
return Err(ProgramError::IncorrectProgramId);
}
// Resolve the enrolled router for the destination domain.
let router = *token
.router(xfer.destination_domain)
.ok_or(ProgramError::InvalidArgument)?;
// Delegate to the shared remote-dispatch helper.
let remote_amount = Self::transfer_remote_to(
program_id,
&token,
system_program_account,
spl_noop,
accounts_iter,
xfer.destination_domain,
xfer.recipient,
router,
xfer.amount_or_id,
)?;
msg!(
"Warp route transfer completed to destination: {}, recipient: {}, remote_amount: {}",
xfer.destination_domain,
xfer.recipient,
remote_amount
);
Ok(())
}
/// Shared remote-dispatch helper: validates mailbox accounts, converts
/// amounts, calls plugin `transfer_in`, dispatches via mailbox CPI, and
/// optionally pays IGP. The caller is responsible for validating
/// system_program, spl_noop, loading the token, and resolving the router.
///
/// Accounts consumed from the iterator (starting after spl_noop / token PDA):
/// - mailbox program
/// - mailbox outbox
/// - dispatch authority PDA
/// - sender wallet (signer)
/// - unique message account
/// - dispatched message PDA
/// - optional IGP accounts
/// - plugin transfer_in accounts
#[allow(clippy::too_many_arguments)]
pub fn transfer_remote_to<'a, 'b>(
program_id: &Pubkey,
token: &HyperlaneToken<T>,
system_program_account: &'a AccountInfo<'b>,
spl_noop: &'a AccountInfo<'b>,
accounts_iter: &mut std::slice::Iter<'a, AccountInfo<'b>>,
destination_domain: u32,
recipient: H256,
router: H256,
amount_or_id: U256,
) -> Result<U256, ProgramError> {
// Mailbox program
let mailbox_info = next_account_info(accounts_iter)?;
if mailbox_info.key != &token.mailbox {
return Err(ProgramError::IncorrectProgramId);
}
// Mailbox Outbox data account.
// No verification is performed here, the Mailbox will do that.
let mailbox_outbox_account = next_account_info(accounts_iter)?;
// Message dispatch authority
let dispatch_authority_account = next_account_info(accounts_iter)?;
let dispatch_authority_seeds: &[&[u8]] =
mailbox_message_dispatch_authority_pda_seeds!(token.dispatch_authority_bump);
let dispatch_authority_key =
Pubkey::create_program_address(dispatch_authority_seeds, program_id)?;
if *dispatch_authority_account.key != dispatch_authority_key {
return Err(ProgramError::InvalidArgument);
}
// Sender account / mailbox payer
let sender_wallet = next_account_info(accounts_iter)?;
if !sender_wallet.is_signer {
return Err(ProgramError::MissingRequiredSignature);
}
// Unique message / gas payment account
// Defer to the checks in the Mailbox / IGP, no need to verify anything here.
let unique_message_account = next_account_info(accounts_iter)?;
// Message storage PDA.
// Similarly defer to the checks in the Mailbox to ensure account validity.
let dispatched_message_pda = next_account_info(accounts_iter)?;
let igp_payment_accounts =
if let Some((igp_program_id, igp_account_type)) = token.interchain_gas_paymaster() {
// The IGP program
let igp_program_account = next_account_info(accounts_iter)?;
if igp_program_account.key != igp_program_id {
return Err(ProgramError::InvalidArgument);
}
// The IGP program data.
// No verification is performed here, the IGP will do that.
let igp_program_data_account = next_account_info(accounts_iter)?;
// The gas payment PDA.
// No verification is performed here, the IGP will do that.
let igp_payment_pda_account = next_account_info(accounts_iter)?;
// The configured IGP account.
let configured_igp_account = next_account_info(accounts_iter)?;
if configured_igp_account.key != igp_account_type.key() {
return Err(ProgramError::InvalidArgument);
}
// Accounts expected by the IGP's `PayForGas` instruction:
//
// 0. `[executable]` The system program.
// 1. `[signer]` The payer.
// 2. `[writeable]` The IGP program data.
// 3. `[signer]` Unique gas payment account.
// 4. `[writeable]` Gas payment PDA.
// 5. `[writeable]` The IGP account.
// 6. `[]` Overhead IGP account (optional).
let mut igp_payment_account_metas = vec![
AccountMeta::new_readonly(system_program::ID, false),
AccountMeta::new(*sender_wallet.key, true),
AccountMeta::new(*igp_program_data_account.key, false),
AccountMeta::new_readonly(*unique_message_account.key, true),
AccountMeta::new(*igp_payment_pda_account.key, false),
];
let mut igp_payment_account_infos = vec![
system_program_account.clone(),
sender_wallet.clone(),
igp_program_data_account.clone(),
unique_message_account.clone(),
igp_payment_pda_account.clone(),
];
match igp_account_type {
InterchainGasPaymasterType::Igp(_) => {
igp_payment_account_metas
.push(AccountMeta::new(*configured_igp_account.key, false));
igp_payment_account_infos.push(configured_igp_account.clone());
}
InterchainGasPaymasterType::OverheadIgp(_) => {
let inner_igp_account = next_account_info(accounts_iter)?;
// The inner IGP is expected first, then the overhead IGP.
igp_payment_account_metas.extend([
AccountMeta::new(*inner_igp_account.key, false),
AccountMeta::new_readonly(*configured_igp_account.key, false),
]);
igp_payment_account_infos
.extend([inner_igp_account.clone(), configured_igp_account.clone()]);
}
};
Some((igp_payment_account_metas, igp_payment_account_infos))
} else {
None
};
let remote_amount = Self::convert_and_transfer_in(
program_id,
token,
sender_wallet,
accounts_iter,
amount_or_id,
)?;
if accounts_iter.next().is_some() {
return Err(ProgramError::from(Error::ExtraneousAccount));
}
// The token message body, which specifies the remote_amount.
let token_transfer_message = TokenMessage::new(recipient, remote_amount, vec![]).to_vec();
// Build mailbox dispatch CPI with explicit router as recipient.
let dispatch_instruction = MailboxInstruction::OutboxDispatch(MailboxOutboxDispatch {
sender: *program_id,
destination_domain,
recipient: router,
message_body: token_transfer_message,
});
let dispatch_account_metas = vec![
AccountMeta::new(*mailbox_outbox_account.key, false),
AccountMeta::new_readonly(*dispatch_authority_account.key, true),
AccountMeta::new_readonly(system_program::ID, false),
AccountMeta::new_readonly(account_utils::SPL_NOOP_PROGRAM_ID, false),
AccountMeta::new(*sender_wallet.key, true),
AccountMeta::new_readonly(*unique_message_account.key, true),
AccountMeta::new(*dispatched_message_pda.key, false),
];
let dispatch_account_infos = &[
mailbox_outbox_account.clone(),
dispatch_authority_account.clone(),
system_program_account.clone(),
spl_noop.clone(),
sender_wallet.clone(),
unique_message_account.clone(),
dispatched_message_pda.clone(),
];
let mailbox_ixn = Instruction {
program_id: token.mailbox,
data: dispatch_instruction
.into_instruction_data()
.map_err(|_| ProgramError::BorshIoError)?,
accounts: dispatch_account_metas,
};
invoke_signed(
&mailbox_ixn,
dispatch_account_infos,
&[dispatch_authority_seeds],
)?;
// Pay for gas if IGP is configured.
if let Some((igp_payment_account_metas, igp_payment_account_infos)) = igp_payment_accounts {
let (igp_program_id, _) = token
.interchain_gas_paymaster()
.ok_or(ProgramError::InvalidArgument)?;
let (returning_program_id, returned_data) =
get_return_data().ok_or(ProgramError::InvalidArgument)?;
if returning_program_id != token.mailbox {
return Err(ProgramError::InvalidArgument);
}
let message_id =
H256::try_from_slice(&returned_data).map_err(|_| ProgramError::InvalidArgument)?;
let destination_gas = token
.destination_gas(destination_domain)
.ok_or(ProgramError::InvalidArgument)?;
let igp_ixn = Instruction::new_with_borsh(
*igp_program_id,
&IgpInstruction::PayForGas(IgpPayForGas {
message_id,
destination_domain,
gas_amount: destination_gas,
}),
igp_payment_account_metas,
);
invoke(&igp_ixn, &igp_payment_account_infos)?;
}
Ok(remote_amount)
}
/// Converts amount from local to remote decimals and calls plugin
/// `transfer_in`. Returns `remote_amount` for the caller to build
/// `TokenMessage`.
pub fn convert_and_transfer_in<'a, 'b>(
program_id: &Pubkey,
token: &HyperlaneToken<T>,
sender_wallet: &'a AccountInfo<'b>,
accounts_iter: &mut std::slice::Iter<'a, AccountInfo<'b>>,
amount_or_id: U256,
) -> Result<U256, ProgramError> {
// The amount denominated in the local decimals.
let local_amount: u64 = amount_or_id
.try_into()
.map_err(|_| Error::IntegerOverflow)?;
// Convert to the remote number of decimals, which is universally understood
// by the remote routers as the number of decimals used by the message amount.
let remote_amount = token.local_amount_to_remote_amount(local_amount)?;
T::transfer_in(
program_id,
token,
sender_wallet,
accounts_iter,
local_amount,
)?;
Ok(remote_amount)
}
/// Accounts:
/// - 0: `[signer]` Mailbox processor authority specific to this program.
/// - 1: `[executable]` system_program
/// - 2: `[]` hyperlane_token storage
/// - 3: `[depends on plugin]` recipient wallet address
/// - 4..N: `[??..??]` Plugin-specific accounts.
pub fn transfer_from_remote(
program_id: &Pubkey,
accounts: &[AccountInfo],
xfer: HandleInstruction,
) -> ProgramResult {
let accounts_iter = &mut accounts.iter();
let mut message_reader = std::io::Cursor::new(xfer.message);
let message = TokenMessage::read_from(&mut message_reader)
.map_err(|_err| ProgramError::from(Error::MessageDecodeError))?;
// Account 0: Mailbox authority
// This is verified further below.
let process_authority_account = next_account_info(accounts_iter)?;
// Account 1: System program
let system_program = next_account_info(accounts_iter)?;
if system_program.key != &system_program::ID {
return Err(ProgramError::InvalidArgument);
}
// Account 2: Token account
let token_account = next_account_info(accounts_iter)?;
let token =
HyperlaneTokenAccount::fetch(&mut &token_account.data.borrow()[..])?.into_inner();
let token_seeds: &[&[u8]] = hyperlane_token_pda_seeds!(token.bump);
let expected_token_key = Pubkey::create_program_address(token_seeds, program_id)?;
if token_account.key != &expected_token_key {
return Err(ProgramError::InvalidArgument);
}
if token_account.owner != program_id {
return Err(ProgramError::IncorrectProgramId);
}
// Account 3: Recipient wallet
let recipient_wallet = next_account_info(accounts_iter)?;
let expected_recipient = Pubkey::new_from_array(message.recipient().into());
if recipient_wallet.key != &expected_recipient {
return Err(ProgramError::InvalidArgument);
}
// Verify the authenticity of the message.
// This ensures the `process_authority_account` is valid and a signer,
// and that the sender is the remote router for the origin.
token.ensure_valid_router_message(process_authority_account, xfer.origin, &xfer.sender)?;
// The amount denominated in the remote decimals.
let remote_amount = message.amount();
// Convert to the local number of decimals.
let local_amount: u64 = token.remote_amount_to_local_amount(remote_amount)?;
// Transfer the `local_amount` of tokens out.
T::transfer_out(
program_id,
&*token,
system_program,
recipient_wallet,
accounts_iter,
local_amount,
)?;
if accounts_iter.next().is_some() {
return Err(ProgramError::from(Error::ExtraneousAccount));
}
msg!(
"Warp route transfer completed from origin: {}, recipient: {}, remote_amount: {}",
xfer.origin,
recipient_wallet.key,
remote_amount
);
Ok(())
}
/// Gets the account metas required by the `HandleInstruction` instruction,
/// serializes them, and sets them as return data.
///
/// Accounts:
/// 0. `[]` The token PDA, which is the PDA with the seeds `HANDLE_ACCOUNT_METAS_PDA_SEEDS`.
pub fn transfer_from_remote_account_metas(
program_id: &Pubkey,
accounts: &[AccountInfo],
transfer: HandleInstruction,
) -> ProgramResult {
let accounts_iter = &mut accounts.iter();
let mut message_reader = std::io::Cursor::new(transfer.message);
let message = TokenMessage::read_from(&mut message_reader)
.map_err(|_err| ProgramError::from(Error::MessageDecodeError))?;
// Account 0: Token account.
let token_account_info = next_account_info(accounts_iter)?;
let token = HyperlaneToken::verify_account_and_fetch_inner(program_id, token_account_info)?;
let (transfer_out_account_metas, writeable_recipient) =
T::transfer_out_account_metas(program_id, &token, &message)?;
let mut accounts: Vec<SerializableAccountMeta> = vec![
AccountMeta::new_readonly(system_program::ID, false).into(),
AccountMeta::new_readonly(*token_account_info.key, false).into(),
AccountMeta {
pubkey: Pubkey::new_from_array(message.recipient().into()),
is_signer: false,
is_writable: writeable_recipient,
}
.into(),
];
accounts.extend(transfer_out_account_metas);
// Wrap it in the SimulationReturnData because serialized account_metas
// may end with zero byte(s), which are incorrectly truncated as
// simulated transaction return data.
// See `SimulationReturnData` for details.
let bytes = borsh::to_vec(&SimulationReturnData::new(accounts))
.map_err(|_| ProgramError::BorshIoError)?;
set_return_data(&bytes[..]);
Ok(())
}
/// Enrolls a remote router.
///
/// Accounts:
/// 0. `[executable]` The system program.
/// 1. `[writeable]` The token PDA account.
/// 2. `[signer]` The owner.
pub fn enroll_remote_router(
program_id: &Pubkey,
accounts: &[AccountInfo],
config: RemoteRouterConfig,
) -> ProgramResult {
let accounts_iter = &mut accounts.iter();
// Account 0: System program. Only used if a realloc / rent exemption top up occurs.
let system_program = next_account_info(accounts_iter)?;
if system_program.key != &system_program::ID {
return Err(ProgramError::InvalidArgument);
}
// Account 1: Token account
let token_account = next_account_info(accounts_iter)?;
let mut token =
HyperlaneTokenAccount::fetch(&mut &token_account.data.borrow()[..])?.into_inner();
let token_seeds: &[&[u8]] = hyperlane_token_pda_seeds!(token.bump);
let expected_token_key = Pubkey::create_program_address(token_seeds, program_id)?;
if token_account.key != &expected_token_key {
return Err(ProgramError::InvalidArgument);
}
if token_account.owner != program_id {
return Err(ProgramError::IncorrectProgramId);
}
// Account 2: Owner
let owner_account = next_account_info(accounts_iter)?;
// This errors if owner_account is not really the owner.
token.enroll_remote_router_only_owner(owner_account, config)?;
// Store the updated token account and realloc if necessary.
HyperlaneTokenAccount::<T>::from(token).store_with_rent_exempt_realloc(
token_account,
&Rent::get()?,
owner_account,
system_program,
)?;
Ok(())
}
/// Enrolls remote routers.
///
/// Accounts:
/// 0. `[executable]` The system program.
/// 1. `[writeable]` The token PDA account.
/// 2. `[signer]` The owner.
pub fn enroll_remote_routers(
program_id: &Pubkey,
accounts: &[AccountInfo],
configs: Vec<RemoteRouterConfig>,
) -> ProgramResult {
let accounts_iter = &mut accounts.iter();
// Account 0: System program. Only used if a realloc / rent exemption top up occurs.
let system_program = next_account_info(accounts_iter)?;
if system_program.key != &system_program::ID {
return Err(ProgramError::InvalidArgument);
}
// Account 1: Token account
let token_account = next_account_info(accounts_iter)?;
let mut token =
HyperlaneTokenAccount::fetch(&mut &token_account.data.borrow()[..])?.into_inner();
let token_seeds: &[&[u8]] = hyperlane_token_pda_seeds!(token.bump);
let expected_token_key = Pubkey::create_program_address(token_seeds, program_id)?;
if token_account.key != &expected_token_key {
return Err(ProgramError::InvalidArgument);
}
if token_account.owner != program_id {
return Err(ProgramError::IncorrectProgramId);
}
// Account 2: Owner
let owner_account = next_account_info(accounts_iter)?;
// This errors if owner_account is not really the owner.
token.enroll_remote_routers_only_owner(owner_account, configs)?;
// Store the updated token account and realloc if necessary.
HyperlaneTokenAccount::<T>::from(token).store_with_rent_exempt_realloc(
token_account,
&Rent::get()?,
owner_account,
system_program,
)?;
Ok(())
}
/// Transfers ownership.
///
/// Accounts:
/// 0. `[writeable]` The token PDA account.
/// 1. `[signer]` The current owner.
pub fn transfer_ownership(
program_id: &Pubkey,
accounts: &[AccountInfo],
new_owner: Option<Pubkey>,
) -> ProgramResult {
let accounts_iter = &mut accounts.iter();
// Account 0: Token account
let token_account = next_account_info(accounts_iter)?;
let mut token = HyperlaneToken::verify_account_and_fetch_inner(program_id, token_account)?;
// Account 1: Owner
let owner_account = next_account_info(accounts_iter)?;
// This errors if owner_account is not really the owner.
token.transfer_ownership(owner_account, new_owner)?;
// Store the updated token account. No need to realloc, the size for the owner is the same.
HyperlaneTokenAccount::<T>::from(token).store(token_account, false)?;
Ok(())
}
/// Gets the interchain security module.
///
/// Accounts:
/// 0. `[]` The token PDA account.
pub fn interchain_security_module(
program_id: &Pubkey,
accounts: &[AccountInfo],
) -> ProgramResult {
let accounts_iter = &mut accounts.iter();
// Account 0: Token account
let token_account = next_account_info(accounts_iter)?;
let token = HyperlaneToken::<T>::verify_account_and_fetch_inner(program_id, token_account)?;
// Set the return data to the serialized Option<Pubkey> representing
// the ISM.
token.set_interchain_security_module_return_data();
Ok(())
}
/// Gets the account metas required to get the ISM, serializes them,
/// and sets them as return data.
///
/// Accounts:
/// None
pub fn interchain_security_module_account_metas(program_id: &Pubkey) -> ProgramResult {
let (token_key, _token_bump) =
Pubkey::find_program_address(hyperlane_token_pda_seeds!(), program_id);
let account_metas: Vec<SerializableAccountMeta> =
vec![AccountMeta::new_readonly(token_key, false).into()];
// Wrap it in the SimulationReturnData because serialized account_metas
// may end with zero byte(s), which are incorrectly truncated as
// simulated transaction return data.
// See `SimulationReturnData` for details.
let bytes = borsh::to_vec(&SimulationReturnData::new(account_metas))
.map_err(|_| ProgramError::BorshIoError)?;
set_return_data(&bytes[..]);
Ok(())
}
/// Lets the owner set the interchain security module.
///
/// Accounts:
/// 0. `[writeable]` The token PDA account.
/// 1. `[signer]` The access control owner.
pub fn set_interchain_security_module(
program_id: &Pubkey,
accounts: &[AccountInfo],
ism: Option<Pubkey>,
) -> ProgramResult {
let accounts_iter = &mut accounts.iter();
// Account 0: Token account
let token_account = next_account_info(accounts_iter)?;
let mut token = HyperlaneToken::verify_account_and_fetch_inner(program_id, token_account)?;
// Account 1: Owner
let owner_account = next_account_info(accounts_iter)?;
// This errors if owner_account is not really the owner.
token.set_interchain_security_module_only_owner(owner_account, ism)?;
// Store the updated token account. No need to realloc, the size for the ISM is the same.
HyperlaneTokenAccount::<T>::from(token).store(token_account, false)?;
Ok(())
}
/// Lets the owner set destination gas configs.
///
/// Accounts:
/// 0. `[executable]` The system program.
/// 1. `[writeable]` The token PDA account.
/// 2. `[signer]` The access control owner.
pub fn set_destination_gas_configs(
program_id: &Pubkey,
accounts: &[AccountInfo],
configs: Vec<GasRouterConfig>,
) -> ProgramResult {
let accounts_iter = &mut accounts.iter();
// Account 0: System program. Only used if a realloc / rent exemption top up occurs.
let system_program = next_account_info(accounts_iter)?;
if system_program.key != &system_program::ID {
return Err(ProgramError::InvalidArgument);
}
// Account 1: Token account
let token_account = next_account_info(accounts_iter)?;
let mut token = HyperlaneToken::verify_account_and_fetch_inner(program_id, token_account)?;
// Account 2: Owner
let owner_account = next_account_info(accounts_iter)?;
// This errors if owner_account is not really the owner.
token.set_destination_gas_configs_only_owner(owner_account, configs)?;
// Store the updated token account and realloc if necessary.
HyperlaneTokenAccount::<T>::from(token).store_with_rent_exempt_realloc(
token_account,
&Rent::get()?,
owner_account,
system_program,
)?;
Ok(())
}
/// Lets the owner set the interchain gas paymaster.
///
/// Accounts:
/// 0. `[writeable]` The token PDA account.
/// 1. `[signer]` The access control owner.
pub fn set_interchain_gas_paymaster(
program_id: &Pubkey,
accounts: &[AccountInfo],
igp: Option<(Pubkey, InterchainGasPaymasterType)>,
) -> ProgramResult {
let accounts_iter = &mut accounts.iter();
// Account 0: Token account
let token_account = next_account_info(accounts_iter)?;
let mut token = HyperlaneToken::verify_account_and_fetch_inner(program_id, token_account)?;
// Account 1: Owner
let owner_account = next_account_info(accounts_iter)?;
// This errors if owner_account is not really the owner.
token.set_interchain_gas_paymaster_only_owner(owner_account, igp)?;
// Store the updated token account. No need to realloc, the size for the ISM is the same.
HyperlaneTokenAccount::<T>::from(token).store(token_account, false)?;
Ok(())
}
}