I am new to Rust.
I am writing a Solana contract and encountered this problem during a CPI (Cross-Program Invocation) call.
I don’t completely understand lifetimes.
I know this is a rust lifetimes issue, but I don’t know how to write the code.
When calling the invoke_signed function, it exceeds the scope of amm.
let mut lamports = 0;
let mut amm_data = [];
let amm = AccountInfo::new(
&amm_pub_key,
false,
false,
&mut lamports,
&mut amm_data,
amm_program.key,
false,
Epoch::default(),
);
invoke_signed(
&ix,
&[
amm.clone(), // When calling this line of code, it exceeds the lifetimes
user_source_owner.clone(),
token_program.clone(),
],
&[],
)?;
The error logs
error[E0597]: `amm_pub_key` does not live long enough
--> src/lib.rs:141:9
|
29 | accounts: &[AccountInfo],
| -------- has type `&[AccountInfo<'1>]`
...
88 | let (amm_pub_key, _bump_seed) = Pubkey::find_program_address(
| ----------- binding `amm_pub_key` declared here
...
140 | let amm = AccountInfo::new(
| _______________-
141 | | &amm_pub_key,
| | ^^^^^^^^^^^^ borrowed value does not live long enough
142 | | false,
143 | | false,
... |
148 | | Epoch::default(),
149 | | );
| |_____- argument requires that `amm_pub_key` is borrowed for `'1`
...
177 | }
| - `amm_pub_key` dropped here while still borrowed
error[E0597]: `lamports` does not live long enough
--> src/lib.rs:144:9
|
29 | accounts: &[AccountInfo],
| -------- has type `&[AccountInfo<'1>]`
...
137 | let mut lamports = 0;//6124800;
| ------------ binding `lamports` declared here
...
140 | let amm = AccountInfo::new(
| _______________-
141 | | &amm_pub_key,
142 | | false,
143 | | false,
144 | | &mut lamports,
| | ^^^^^^^^^^^^^ borrowed value does not live long enough
... |
148 | | Epoch::default(),
149 | | );
| |_____- argument requires that `lamports` is borrowed for `'1`
...
177 | }
| - `lamports` dropped here while still borrowed
error[E0597]: `amm_data` does not live long enough
--> src/lib.rs:145:9
|
29 | accounts: &[AccountInfo],
| -------- has type `&[AccountInfo<'1>]`
...
138 | let mut amm_data = [];
| ------------ binding `amm_data` declared here
139 |
140 | let amm = AccountInfo::new(
| _______________-
141 | | &amm_pub_key,
142 | | false,
143 | | false,
144 | | &mut lamports,
145 | | &mut amm_data,
| | ^^^^^^^^^^^^^ borrowed value does not live long enough
... |
148 | | Epoch::default(),
149 | | );
| |_____- argument requires that `amm_data` is borrowed for `'1`
...
177 | }
| - `amm_data` dropped here while still borrowed
**I want to know how to write the correct code?
**