Skip to content

Instantly share code, notes, and snippets.

View danmt's full-sized avatar
👽
Doing mah thing.

Daniel Marin danmt

👽
Doing mah thing.
View GitHub Profile
@danmt
danmt / as-observable-factory.ts
Last active December 22, 2023 12:07
Turn Factory of Promises into an Observable Factory
type AsObservableFactory<T> = T extends (...a: infer U) => Promise<infer V>
? (...a: U) => Observable<V>
: never;
@danmt
danmt / metadata_id.rs
Created September 16, 2023 21:33
Initialize a Metadata struct with the Token Metadata program id.
#[derive(Clone)]
pub struct Metadata;
impl anchor_lang::Id for Metadata {
fn id() -> Pubkey {
Pubkey::from_str("metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s").unwrap()
}
}
@danmt
danmt / union-by.ts
Last active September 19, 2023 13:22
Create a Mapped Type from a Discriminated Union
// Union method to create a mapped typed from a discriminated union
export type UnionBy<
Key extends string,
Value extends string,
Base,
Map extends Record<Value, object | null>
> = {
[TValue in keyof Map]: {
[key in Key]: TValue;
} & (Map[TValue] extends null ? Base : Base & Map[TValue]);
@danmt
danmt / handle-unchecked-accounts.rs
Last active August 10, 2023 14:24
Dealing with unchecked accounts in Solana
pub fn is_discriminator_already_set<'info>(account: &UncheckedAccount<'info>) -> Result<bool> {
let data = account.try_borrow_data()?;
let mut disc_bytes = [0u8; 8];
disc_bytes.copy_from_slice(&data[..8]);
let discriminator = u64::from_le_bytes(disc_bytes);
Ok(discriminator != 0)
}
pub fn try_deserialize_unchecked<'info, T: AccountDeserialize>(
account: &UncheckedAccount<'info>,
@danmt
danmt / get_remaining_account.rs
Created April 16, 2022 20:26
Get an instruction account from the remaining accounts list and decode it, bubble up in case of errors.
pub fn get_remaining_account<'info, T: AccountSerialize + AccountDeserialize + Owner + Clone>(
remaining_accounts: &[AccountInfo<'info>],
index: usize,
) -> std::result::Result<Option<Account<'info, T>>, Error> {
let maybe_account: Option<&AccountInfo> = remaining_accounts.get(index);
let maybe_decoded_account: Option<std::result::Result<Account<'info, T>, Error>> =
maybe_account.map(Account::try_from);
match maybe_decoded_account {
Some(Ok(account)) => Ok(Some(account)),
Some(Err(_)) => return Err(error!(ErrorCode::InvalidAccount)),