@drift-labs/sdk
Version:
SDK for Drift Protocol
65 lines (64 loc) • 2.52 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.CustomBorshAccountsCoder = exports.CustomBorshCoder = void 0;
const buffer_1 = require("buffer");
const anchor_1 = require("../isomorphic/anchor");
class CustomBorshCoder {
constructor(idl) {
const baseCoder = new anchor_1.BorshCoder(idl);
this.instruction = baseCoder.instruction;
this.accounts = new CustomBorshAccountsCoder(idl);
this.events = baseCoder.events;
this.types = baseCoder.types;
this.idl = idl;
}
}
exports.CustomBorshCoder = CustomBorshCoder;
/**
* Custom accounts coder that wraps BorshAccountsCoder to fix encode buffer sizing.
*/
class CustomBorshAccountsCoder {
constructor(idl) {
this.baseCoder = new anchor_1.BorshAccountsCoder(idl);
this.idl = idl;
}
async encode(accountName, account) {
const layout = this.baseCoder['accountLayouts'].get(accountName);
if (!layout) {
throw new Error(`Unknown account: ${accountName}`);
}
// Fix: compute proper buffer size instead of the hardcoded 1000 bytes
const size = this.baseCoder.size(accountName);
const buffer = buffer_1.Buffer.alloc(Math.max(size, 1000));
const len = layout.layout.encode(account, buffer);
const accountData = buffer.slice(0, len);
const discriminator = buffer_1.Buffer.from(layout.discriminator);
return buffer_1.Buffer.concat([discriminator, accountData]);
}
// Delegate all other methods to the base coder
decode(accountName, data) {
return this.baseCoder.decode(accountName, data);
}
decodeAny(data) {
return this.baseCoder.decodeAny(data);
}
decodeUnchecked(accountName, ix) {
return this.baseCoder.decodeUnchecked(accountName, ix);
}
memcmp(accountName, appendData) {
return this.baseCoder.memcmp(accountName, appendData);
}
size(accountName) {
return this.baseCoder.size(accountName);
}
/**
* Calculates and returns a unique 8 byte discriminator prepended to all anchor accounts.
*
* @param name The name of the account to get the discriminator of.
*/
static accountDiscriminator(_name) {
// Delegate to an instance method since anchor 0.32 uses IDL discriminators
throw new Error('accountDiscriminator requires an instance; use coder.accountDiscriminator(name)');
}
}
exports.CustomBorshAccountsCoder = CustomBorshAccountsCoder;