0 purchases
solana borsh
Dart implementation of the Borsh serializer. #
import 'package:solana_borsh/borsh.dart';
import 'package:solana_borsh/codecs.dart';
import 'package:solana_borsh/models.dart';
import 'package:solana_borsh/types.dart';
void main() {
final myObject = MyObject(
u8: 255,
u16: null,
u32: 4294967295,
u64: BigInt.parse('18446744073709551615'),
string: 'Hello',
stringSized: 'Hello 7',
array: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
vec: [BigInt.zero, BigInt.one, BigInt.two],
);
final Iterable<int> encoded = myObject.toBorsh();
final MyObject decoded = borsh.deserialize(myObject.borshSchema, encoded, MyObject.fromJson);
}
class MyObject extends BorshObject {
MyObject({
required this.u8,
required this.u16,
required this.u32,
required this.u64,
required this.string,
required this.stringSized,
required this.array,
required this.vec,
});
final int u8;
final int? u16; // optional value.
final int? u32; // optional value.
final BigInt u64;
final String string;
final String stringSized; // Fixed-length string.
final List<int> array; // Fixed-length list.
final List<BigInt> vec; // Dynamic-length list.
@override
BorshSchema get borshSchema => borshCodec.schema;
static BorshStructCodec get borshCodec => BorshStructCodec({
'u8': borsh.u8,
'u16': borsh.u16.option(),
'u32': borsh.u32.cOption(), // 4-byte optional flag.
'u64': borsh.u64,
'string': borsh.string(),
'stringSized': borsh.stringSized(7),
'array': borsh.array(borsh.i64, 10),
'vec': borsh.vec(borsh.u64),
});
@override
factory MyObject.fromJson(final Map<String, dynamic> json) => MyObject(
u8: json['u8'],
u16: json['u16'],
u32: json['u32'],
u64: json['u64'],
string: json['string'],
stringSized: json['stringSized'],
array: json['array'],
vec: json['vec'],
);
@override
Map<String, dynamic> toJson() => {
'u8': u8,
'u16': u16,
'u32': u32,
'u64': u64,
'string': string,
'stringSized': stringSized,
'array': array,
'vec': vec,
};
}
copied to clipboard
For personal and professional use. You cannot resell or redistribute these repositories in their original state.
There are no reviews.