uses SysUtils;

const
  ITEM_ID: 21735;         // ID of the item we want to break into crystals (21735=Тарбар)
  ITEM_PRICE = 1540000;   // the purchase price of this item in the store

// https://adrenalinebot.com/en/api/example/counting-the-number-of-items-in-the-inventory
function ItemCount(id: integer): int64;  overload;     // counting items by ID
var i: integer;
begin
  result:= 0;                                          
  for i:= 0 to Inventory.User.Count-1 do begin         // go over the user's inventory
    if (Inventory.User.Items(i).ID = id) then          // if id matched, then
      Inc(result, Inventory.User.Items(i).Count);      // increase the result by the number of items in the stack
  end; 
end;

// Wrap function for buying items from merchant with npc_id, items - an array of what you need to buy
procedure BuyItemsFromNPC(npc_id: integer; items: array of integer);   
begin                                                  
  Engine.SetTarget(npc_id);                            // take merchant in the target
  Engine.DlgOpen;                                      // open dialog with the merchant
  Engine.DlgSel(2);                                    // click on the line of purchase (the ordinal number of the line)
  Engine.NpcTrade(false, items);                       // the first argument false means the purchase, the second - the shopping list
end;

begin
  if (User.CanCryst) then begin                        // if our character can crystallize objects
    // here you can run up to the NPC if required
    // Engine.MoveTo(....);
    while (ItemCount(57) > ITEM_PRICE) do begin        // if we have enough adena to buy an item, then
      BuyItemsFromNPC(30084, [ITEM_ID, 1]);            // buy from NPC (Graham in Giran) the desired item
      if Engine.CrystalItem(ITEM_ID) then delay(999);  // we break it into crystals, and if we succeed, then we wait a little
    end;
  end else Print('Our character cannot crystallize items!');
  
end.